[Selfless sharing: ASP. net core Project Practice (chapter 7)] File Operation FileHelper,

Source: Internet
Author: User

[Selfless sharing: ASP. net core Project Practice (chapter 7)] File Operation FileHelper,
Directory Index

 

[Selfless sharing: ASP. net core project practice] Directory Indexing

 

Introduction

 

In program design, we often use file operations. In the previous series, we have many basic file operation examples with some changes in Core, we usually use Server. mapPath () does not exist. I don't know if it will be available in subsequent versions. Here, we can only encapsulate the method to implement it. Today, we have written a FileHelper class for some basic operations for your discussion.

 

 

Obtain the absolute path of a file

 

In the previous operations, this should be very simple, you can use the System. web. httpContext. current. server. mapPath ("... ") Get it directly. As we mentioned in the introduction, this method does not exist anymore. I read a lot of information online, Server. mapPath finally calls HostingEnvironment. mapPath (). However, it creates a virtualpath object for a specific option. Let's take a look at how to implement these principles for the moment.

  

Here we need to use IHostingEnvironment. There are many injection methods. The most recommended method is constructor injection. For example:

Public readonly IHostingEnvironment _ Env;

Public FileHelper (IHostingEnvironment Env)
{
_ Env = Env;
}

 

However, in reality, we hope that all the methods in this class are static methods, and FileHelper can be called directly. mapPath (), of course, this is not the main factor. The main factor is that we need to call this method in other help classes, for example, we have a method in the Uitls class to read the file content and call this method to obtain the absolute path. In both cases, constructor injection is obviously inappropriate.

So how can we implement it?

I. we add two static classes Extensions and DI.

 

 

2. Add:

 

 

After adding these two classes, we return to FileHelper

Define two static fields:

DirectorySeparatorChar: Directory separator. Because it is a cross-platform application, we need to determine the directory separator. It is "\" in windows and "/" in Mac OS and Linux "/"

_ ContentRootPath: the absolute path of the directory containing the application

  

  

Now we can write a static method MapPath (string path) to obtain the absolute path of the file)

Logic: ①: determines whether it is an absolute path. If it is an absolute path, the current path is directly returned.

②: If it is not an absolute Path, we use the Path. Combine combination Path, the absolute Path of the application directory + the virtual Path to the absolute Path

  

/// <Summary>
/// Obtain the absolute path of the object
/// </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 ));
}

 

Note:

_ ContentRootPath is the absolute path of the application we started to obtain. private static string _ ContentRootPath = DI. ServiceProvider. GetRequiredService <IHostingEnvironment> (). ContentRootPath;

For the passed path, we first use TrimStart to remove "~" from the path. And "/", and then Replace the directory separator with the directory Separator of the current system through Replace

IsAbsolute is a defined method to determine whether the current path is an absolute path (see the following section)

 

Determine whether the current path is an absolute path

We used a simple method to determine whether the current path is an absolute path. We obtained the system drive letter. The windows system drive letter is ":". mac OS and Linux do not have a drive letter concept starting with "/", so we can determine whether it contains "\":

1 /// <summary> 2 /// whether it is an absolute path. 3 // in windows, check whether the path contains ": "4 // check whether the path contains Mac OS or Linux" \ "5 // </summary> 6 // <param name =" path "> path </ 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 file operations (these operations are basically the same as before, for your reference)

  

All paths are used in IsAbsolute (path )? Path: MapPath (path), a ternary operator. You can determine if a non-absolute path is converted to an absolute path.

Check whether the specified path exists:

  

1 /// <summary> 2 /// check whether the specified path exists 3 /// </summary> 4 /// <param name = "path"> path </param> 5 // <param name = "isDirectory"> whether it is 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"> path </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 a directory or file 3 /// </summary> 4 /// <param name = "path"> path </param> 5 // <param name = "isDirectory"> whether it is 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 else14 {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 a file or directory

 

1 // <summary> 2 // delete a directory or file 3 /// </summary> 4 // <param name = "path"> path </param> 5 // <param name = "isDirectory"> whether it is 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 else15 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, still keep this 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 and move files

1 /// <summary> 2 /// copy the file content to the target folder 3 /// </summary> 4 /// <param name = "sourcePath"> source file </ param> 5 // <param name = "targetPath"> Target folder </param> 6 /// <param name = "isOverWrite"> 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 the file to the target 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 // if the target directory does not exist, create 10 if (! IsExist (targetPath, true) 11 {12 CreateFiles (targetPath, true); 13} 14 else15 {16 // Delete 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 the 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 the file name without the 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 // obtain the 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}

 

 

Fixed:

  

If it is an absolute path, we have made a judgment in the MapPath (string path) method, so there is no need to judge it again for other methods. IsAbsolute (path) in other methods )? Path: MapPath (path) can be changed directly to MapPath (path ),

Thank you @ shoufengwei!

 

 

 

 

 

I hope to study Asp.net Core with you.

At the beginning, there was a limited level of contact, and many things were self-understanding and reading the information of the great gods on the Internet. If there is something wrong or incomprehensible, I hope you can correct it!

Although Asp.net Core is very popular now, many materials on the Internet are copied in the previous article, so I have not solved many problems for the time being. I hope you can help me together!

 

Original article reprinted please respect labor results http://yuangang.cnblogs.com

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.