Analysis on the Operation of File Path in C

  • 2021-11-13 17:59:44
  • OfStack

It is very common to operate on files in programs, but the operation on files inevitably requires the path of files, and carries out a series of operations on the path of files, such as judging whether the known path is a directory or a file, what is the name of the file if the path is a file, and what is the extension name of the file, etc. In C #, the file path is not abstracted as a class, which means that the file path is an ordinary string. Operations on a file path, for example, to get a file name, can be obtained by truncating a string or using a regular expression.

In fact, in the. NET class library, there is a special functional class System. IO. Path, which operates on string representing files or directory paths. Here are some common operations on file paths by using Path.

Judge whether the given path or file name is legal or not

Path. GetInvalidFileNameChars () This method returns 1 character that char [] indicates cannot appear in the file name.


/// <summary>
  ///  Determine whether the file name is legal or not 
  /// </summary>
  /// <param name="fileName"> Filename </param>
  /// <returns>ture , legal; false , illegal </returns>
  public bool validFileName(string fileName)
  {
   if(!string.IsNullOrEmpty(fileName))
   {
    char [] errChars = Path.GetInvalidFileNameChars() ;
    foreach(char ch in errChars)
    {
     if(fileName.Contains(ch.ToString()))
      return false ;
    }
   }
   else
   {
    return false ;
   }
   return true ;
  }

If the file name is illegal, you can remove the illegal characters by using the following methods


/// <summary>
  ///  Get rid of illegal characters in file names 
  /// </summary>
  /// <param name="fileName"></param>
  /// <returns> Legal file name </returns>
  public string fixedFileName(string fileName)
  {
   char[] errChars = Path.GetInvalidFileNameChars();
   StringBuilder fileNameBuilder = new StringBuilder(fileName) ;
   foreach(char ch in errChars)
   {
    fileNameBuilder.Replace(ch.ToString(),string.Empty);
   }
   return fileNameBuilder.ToString();
  }

Similarly, Path. GetInvalidPathChars () is used to obtain characters that cannot appear in the directory path, to judge whether the given directory path is legal, and to modify the illegal directory path.

Determine whether the given path is a directory path or a file path

If you can determine that the given path already exists, you can use Directory. Exists () and File. Exists () to determine whether the path is a directory or a file. If you can't determine the existence of a given path, you can use Path. GetFileName () to get the file name in the path. If you can get the file name, it is obvious that the path is a file path, and if you can't, it is a path. Explain that the last 1 character of the directory path should end with '\'.

Merge path

Different parts of some paths are taken from different places, so it is necessary to combine these parts to form a complete path. Inevitably, the process of combining involves the processing of "\", so you can use Path. Combine () to combine different parts of the path into one. Path. Combine () has many forms of overloading to meet different requirements. It should be noted that when using Path. Combine (), illegal file names or pathnames are not accepted, and when merging, if a certain part starts from an absolute path, the merging operation is reset to start from the absolute path, and the previous merged path is discarded. For example:


string[] paths = {@"d:\archives", "2001", "e:\\", "images"};
   string fullPath = Path.Combine(paths);
   //fullPath  For  e:\images
   Console.WriteLine(fullPath);
fullPath For e:\images

Get specific parts of the path, such as file name, extension, file directory, and so on


   Path.GetFileName(path);// Get the file name  
   Path.GetFileNameWithoutExtension(path); // Get the file name without extension  
   Path.GetExtension(path) ; // Get the file extension  
   Path.GetDirectoryName(path) ; // Get the file directory  
   Path.GetPathRoot(path) ;// Get root directory information 

For more details, please refer to MSDN http://msdn.microsoft.com/zh-cn/library/system.io.path _ methods. aspx

Some other functions of Path

Path. GetRandomFileName () Gets a random file name or directory name Path. GetTempFileName () Creates a 1-named zero-byte temporary file on disk and returns the full path to the file Path. GetTempPath () Gets the temporary directory path for the current user Path. HasExtension () determines whether the path contains a file extension

Get the path related to the application

System. Diagnostics. Process. GetCurrentProcess (). MainModule. FileName Get the full path of the module, including the file name. System. Environment. CurrentDirectory Gets or sets the fully qualified path to the application's current working directory System. IO. Directory. GetCurrentDirectory () Gets or sets the current working directory of the application, not the starting directory of the application, but the directory where the application was last operated.

Correlation of environmental variables

Use System. Environment. GetEnvironmentVariable () to get file paths related to environment variables, such as:

System. Environment. GetEnvironmentVariable ("windir") Get the directory where the operating system is located System. Environment. GetEnvironmentVariable ("INCLUDE") Gets the directory where the header file is located System. Environment. GetEnvironmentVariable ("TMP") Get temporary directory System. Environment. GetEnvironmentVariable ("Path") Gets the directory of files contained in the Path environment variable

Naturally, you can set environment variables using System. Environment. SetEnvironmentVariable ()


Related articles: