[selfless sharing: ASP.NET Core project actual combat (Chapter 7)] file operation FileHelper

Original text: [selfless sharing: ASP.NET Core project actual combat (Chapter 7)] file operation FileHelper

 

Catalog Index

 

[selfless sharing: ASP.NET Core project actual combat] directory index

 

brief introduction

 

In programming, in many cases, we will use the operation of files Previous series In, we have many examples of basic file operations, and there are some changes in the Core, mainly the common Server.MapPath() no longer exists. I don't know if there will be any later versions. Here, we can only encapsulate methods to implement it. Today, we write a FileHelper class for some basic operations for you to discuss. I would like to thank God for his help @YINYEJUN

 

 

Get the absolute path of the file

 

In the previous operation, this should be very simple. You can use the System.Web.HttpContext.Current.Server.MapPath("...") get it directly. In the introduction, we said that this method no longer exists. We have browsed a lot of materials on the Internet, Server.MapPath Final call HostingEnvironment.MapPath() , but it creates a virtualpath object for a specific option. Let's ignore these principles for the moment and see how to implement them.

  

We need to use IHostingEnvironment here. There are many ways to inject. The most recommended one is constructor injection, for example:

    public readonly IHostingEnvironment _Env;

    public FileHelper(IHostingEnvironment Env)
    {
      _Env = Env;
    } 


 

However, the reality is that we want the methods in this class to be static methods, which can be called directly FileHelper.MapPath(), of course, this is not the main factor. The main factor is that we need to call this method in other help classes, such as the Uitls class There is a method called to read the contents of the file to obtain the absolute path. In two cases, the injection of the constructor is obviously not appropriate.

So, how can we achieve it?

1: We add two static classes, Extensions and DI

 

 

2: At Startup.cs In the Configure method of:

 

 

After adding these two classes, let's go back to FileHelper

Define two static fields:

DirectorySeparatorChar: Directory separator, because it is a cross platform application, we need to judge the directory separator, which is "\" under windows, and "/" under Mac OS and Linux

     _ ContentRootPath: absolute path to the directory containing the application

  

  

Let's write a static method MapPath(string path) to get the absolute path of the file

The logic is: ①: judge whether it is an absolute path. If it is an absolute path, directly return to the current path

②: if it is not an absolute path, we pass Path.Combine Combined path, absolute path of application directory + virtual path to absolute path

  

  /// <summary>
/ / / get file absolute path
  /// </summary>
/ / / < param name = "path" > file path < / param >
  /// <returns></returns>
  public static string MapPath(string path)
  {
    return IsAbsolute(path) ? path : Path.Combine(_ContentRootPath , path.TrimStart('~','/').Replace("/", DirectorySeparatorChar));
  }







 

explain:

A kind of Contentrootpath is the absolute path of the application we are getting at the beginning. Private static string_ ContentRootPath = DI.ServiceProvider.GetRequiredService <IHostingEnvironment>().ContentRootPath;

For the path passed in, we first remove "~" and "/" in the path with TrimStart, and then Replace the directory separator with the directory separator of the current system with Replace

IsAbsolute is our defined method to determine whether the current path is an absolute path (see below)

 

Determine whether the current path is an absolute path

We use a simple method to judge whether the current path is an absolute path. We get the system drive letter, which is': 'for windows; the concept of no drive letter for Mac OS and Linux starts with' / ', so we judge whether it contains' \':

      

 1      /// <summary>
 2         /// Is it an absolute path
 3         /// windows Determine whether the path contains ":"
 4         /// Mac OS,Linux Determine whether the path contains "\"
 5         /// </summary>
 6         /// <param name="path">route</param>
 7         /// <returns></returns>
 8         public static bool IsAbsolute(string path)
 9         {
10             return Path.VolumeSeparatorChar == ':' ? path.IndexOf(Path.VolumeSeparatorChar) > 0 : path.IndexOf('\\') > 0;
11         }

 

 

 

 

Basic operations of documents (these operations are basically the same as before, for your reference)

  

For all paths, we use isabsolute (path)? Path: mappath (path), a ternary operator. The user judges that if the non absolute path turns to the absolute path.

Check whether the specified path exists:

  

 1 /// <summary>
 2         /// Check whether the specified path exists
 3         /// </summary>
 4         /// <param name="path">route</param>
 5         /// <param name="isDirectory">Is it a directory</param>
 6         /// <returns></returns>
 7         public static bool IsExist(string path,bool isDirectory)
 8         {
 9             return isDirectory ? Directory.Exists(IsAbsolute(path) ? path : MapPath(path)) : File.Exists(IsAbsolute(path) ? path : MapPath(path));
10         }

 

Check whether the directory is empty

 

1 /// <summary>
2         /// Check whether the directory is empty
3         /// </summary>
4         /// <param name="path">route</param>
5         /// <returns></returns>
6         public static bool IsEmptyDirectory(string path)
7         {
8             return Directory.GetFiles(IsAbsolute(path) ? path : MapPath(path)).Length <= 0 && Directory.GetDirectories(IsAbsolute(path) ? path : MapPath(path)).Length <= 0;
9         }

 

 

Create a file or directory

 

 1 /// <summary>
 2         /// Create directory or file
 3         /// </summary>
 4         /// <param name="path">route</param>
 5         /// <param name="isDirectory">Is it a directory</param>
 6         public static void CreateFiles(string path, bool isDirectory)
 7         {
 8             try {
 9                 if (!IsExist(path, isDirectory))
10                 {
11                     if (isDirectory)
12                         Directory.CreateDirectory(IsAbsolute(path) ? path : MapPath(path));
13                     else
14                     {
15                         FileInfo file = new FileInfo(IsAbsolute(path) ? path : MapPath(path));
16                         FileStream fs = file.Create();
17                         fs.Dispose();
18                     }
19                 }                   
20             }
21             catch(Exception ex)
22             {
23                 throw ex;
24             }
25         }

 

 

Delete file or directory

 

 1 /// <summary>
 2         /// Delete directory or file
 3         /// </summary>
 4         /// <param name="path">route</param>
 5         /// <param name="isDirectory">Is it a directory</param>
 6         public static void DeleteFiles(string path, bool isDirectory)
 7         {
 8             try
 9             {
10                 if (!IsExist(path, isDirectory))
11                 {
12                     if (isDirectory)
13                         Directory.Delete(IsAbsolute(path) ? path : MapPath(path));
14                     else
15                         File.Delete(IsAbsolute(path) ? path : MapPath(path));                    
16                 }
17             }
18             catch (Exception ex)
19             {
20                 throw ex;
21             }
22         }

 

Clear all files and subdirectories in the directory and keep the directory

  

 1 /// <summary>
 2         /// Clear all files and subdirectories in the directory and keep the directory
 3         /// </summary>
 4         /// <param name="path"></param>
 5         public static void ClearDirectory(string path)
 6         {
 7             if(IsExist(path,true))
 8             {
 9                 //All files in the directory
10                 string[] files = Directory.GetFiles(IsAbsolute(path) ? path : MapPath(path));
11                 foreach(var file in files)
12                 {
13                     DeleteFiles(file, false);
14                 }
15                 //All subdirectories under the directory
16                 string[] directorys = Directory.GetDirectories(IsAbsolute(path) ? path : MapPath(path));
17                 foreach(var dir in directorys)
18                 {
19                     DeleteFiles(dir, true);
20                 }
21             }
22         }

 

Copy files, move files

 1 /// <summary>
 2         /// Copy file contents to destination folder
 3         /// </summary>
 4         /// <param name="sourcePath">source file</param>
 5         /// <param name="targetPath">Destination folder</param>
 6         /// <param name="isOverWrite">Can I overwrite</param>
 7         public static void Copy(string sourcePath,string targetPath,bool isOverWrite=true)
 8         {
 9             File.Copy(IsAbsolute(sourcePath) ? sourcePath : MapPath(sourcePath), (IsAbsolute(targetPath) ? targetPath : MapPath(targetPath))+ GetFileName(sourcePath), isOverWrite);
10         }

 

 

 1 /// <summary>
 2         /// Move files to destination directory
 3         /// </summary>
 4         /// <param name="sourcePath">source file</param>
 5         /// <param name="targetPath">Target directory</param>
 6         public static void Move(string sourcePath, string targetPath)
 7         {
 8             string sourceFileName = GetFileName(sourcePath);
 9             //Create if target directory does not exist
10             if(!IsExist(targetPath, true))
11             {
12                 CreateFiles(targetPath, true);
13             }
14             else
15             {
16                 //Delete if a file with the same name exists in the target directory
17                 if (IsExist(Path.Combine(IsAbsolute(targetPath) ? targetPath : MapPath(targetPath), sourceFileName), false))
18                 {
19                     DeleteFiles(Path.Combine(IsAbsolute(targetPath) ? targetPath : MapPath(targetPath), sourceFileName), true);
20                 }
21             }
22 
23             File.Move(IsAbsolute(sourcePath) ? sourcePath : MapPath(sourcePath), Path.Combine(IsAbsolute(targetPath) ? targetPath : MapPath(targetPath), sourceFileName));
24 
25 
26         }

 

Get file name and extension

 1 /// <summary>
 2         /// Get file name and extension
 3         /// </summary>
 4         /// <param name="path">File path</param>
 5         /// <returns></returns>
 6         public static string GetFileName(string path)
 7         {
 8             return Path.GetFileName(IsAbsolute(path) ? path : MapPath(path));
 9         }
10 
11         /// <summary>
12         /// Get filename without extension
13         /// </summary>
14         /// <param name="path">File path</param>
15         /// <returns></returns>
16         public static string GetFileNameWithOutExtension(string path)
17         {
18             return Path.GetFileNameWithoutExtension(IsAbsolute(path) ? path : MapPath(path));
19         }
20         
21         /// <summary>
22         /// Get file extension
23         /// </summary>
24         /// <param name="path">File path</param>
25         /// <returns></returns>
26         public static string GetFileExtension(string path)
27         {
28             return Path.GetExtension(IsAbsolute(path) ? path : MapPath(path));
29         }

 

 

Amendment:

  

For absolute path, we have made a judgment in MapPath(string path) method, so other methods do not need to judge again. In other methods, isabsolute (path)? Path: MapPath(path) can be directly changed to MapPath(path),

Thank you @ shoufengwei!

 

 

 

  

 

 

Hope to learn with you Asp.net Core 

Just started to contact, the level is limited, many things are their own understanding and browsing the online God of information, if there is something wrong and do not understand, I hope you correct!

although Asp.net Core is very hot now, but many materials on the Internet are the same copy of the previous article, so there are many problems I haven't solved yet, I hope you can help!

 

Please respect the achievements of labor http://yuangang.cnblogs.com

Tags: Mac Windows Linux Programming

Posted on Sun, 24 May 2020 08:42:03 -0400 by Desertwar