Asp. NET file operations (file information, new, move, copy, rename, upload, traverse) (pro-Test details)

Source: Internet
Author: User
Tags throw exception

do a few days of file operation, now to summarize, the error, but also hope pointing! For example, if you are working with a folder, you can basically replace file with directory (for example:FileInfo file = new FileInfo (Path); With DirectoryInfo directory = new DirectoryInfo (Path);)

1 Getting file information

The following code can get the details of a file in the case of knowing the relative path of the file

1           Public Staticvoid FileInfo (stringPath)2         {3Path = Server.MapPath (path);//get the physical path of a file4FileInfo file =NewFileInfo (Path);//instance the path file information5             varLength=file. Length;//file size, bytes6             varName = file. Name;//file name7             varFullName = file. FullName;//file path8             varExtension = file. Extension;//file suffix name9......
Ten}

The information obtained also has the creation time, the last visit time and so on, can study independently

2 new File

Create a new file

1        Publicstatic void NewFile (stringFilePath)2         {3Filepath=server.mappath (FilePath);//get the physical path to the file you want to create4             if(System.IO.File.Exists (newfilepath))5             {6                 //determine if a new file already exists7                 Throw NewException ("file already exists")8             }9 TenSystem.IO.File.Create (Newfilepath);//Create One             ...... A}

3 Copy files, move (cut) files, rename files

To copy a file:

1          Publicstatic void Copy (stringPath,stringTargetPath)2         {3Path = Server.MapPath (path);//the physical path of the original file4TargetPath = Server.MapPath (TargetPath);//the physical path to the new location to copy to5             //determine if a new address exists to rename the file6             if(System.IO.File.Exists (TargetPath))7             {8                 Throw NewException ("There is a file with the same name");//Throw Exception9             }        
TenSystem.IO.File.Copy (Path,targetpath);//Copy to new location, overwriting existing files is not allowed One ....... A}

To move a file, rename it:

1       Publicstatic void Moveorrename (stringPath,stringTargetPath)2         {3Path = Server.MapPath (path);//the physical path of the original file4TargetPath = Server.MapPath (TargetPath);//The physical path to the new location to which the file will be renamed if it is still the current folder5             //determine if a new address exists to rename the file6             if(System.IO.File.Exists (TargetPath))7             {8                 //determine if the new location exists with the same name (judging that renaming is a dog and other file conflicts)9                 Throw NewException ("A file with the same name already exists");Ten             }
OneSystem.IO.File.Move (Path,targetpath);//2 files are moved in different directories, if they are renamed in the same directory A ...... -}

Copying files will not be deleted, moved or renamed (the same way, the target location is different) will delete the original file.

4 Uploading files

1[HttpPost]//receive file data from the foreground via POST request2          PublicActionResult UploadFile (stringDirpath)3         {4             varfilepath = Server.MapPath (Path);//gets the physical path of the uploaded file to the directory5             varFile = request.files["file"];//Get file Contents6             if(File = =NULL|| File. ContentLength = =0)7             {8                 Throw NewException ("file does not exist");//simple judgment on the file9             }Ten             varNewfilepath = Server.MapPath (Dirpath +"\\"+ file. FileName);//gets the physical path of the file name One             //determine if the file to be uploaded is renamed to a file in the directory A             if(System.IO.File.Exists (newfilepath)) -             { -                 Throw NewException ("file does not exist");//simply determine if the file exists the             } -             //The file is stored in the specified file; - file. SaveAs (Newfilepath); -             ...... +}

Automatically creates a file containing the class size and name, without superfluous to create a new file and put it into the content.

5 traversing all files in the current directory and its subdirectories

1       Private Static string[] GetFiles (stringDirstringRegexpattern =NULL,BOOLRecurse =true,BOOLThrowex =false)2         {3             //recurse: Whether recursive4             //Throwex: Whether to report an exception5list<string> LST =Newlist<string>();6             Try7             {8                 foreach(stringIteminchdirectory.getfilesystementries (dir))9                 {Ten                     Try One                     { A                         BOOLIsfile = (System.IO.File.GetAttributes (item) & fileattributes.directory)! =fileattributes.directory; -  -                         if(Isfile && (Regexpattern = =NULL|| Regex.IsMatch (Path.getfilename (item), Regexpattern, Regexoptions.ignorecase |regexoptions.multiline ))) the {lst. ADD (item); } -  -                         //Recursive -                         if(Recurse &&!isfile) {lst. AddRange (GetFiles (item, Regexpattern,true)); } +                     } -                     Catch{if(Throwex) {Throw; } } +                 } A             } at             Catch{if(Throwex) {Throw; } } -  -             returnlst. ToArray (); -}

This is not much to say, the code found online, pro-test effective.

Asp. NET file operations (file information, new, move, copy, rename, upload, traverse) (pro-Test details)

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.