asp.net common file and folder action classes

Source: Internet
Author: User
Tags httpcontext

ASP tutorial. NET common File and folder action classes

#region Reference namespaces


Using System;


Using System.Collections.Generic;


Using System.Text;


Using System.IO;


#endregion


Namespace Commonutilities


{


<summary>


File Action Class


</summary>


public class Filehelper


{


#region detect if a specified directory exists


<summary>


Detects if a specified directory exists


</summary>


Absolute path </param> of <param name= "DirectoryPath" > Directory


public static bool Isexistdirectory (string directorypath)


{


Return directory.exists (DirectoryPath);


}


#endregion


#region detect if the specified file exists


<summary>


Detects whether the specified file exists, and returns true if it exists.


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static bool Isexistfile (string FilePath)


{


Return file.exists (FilePath);


}


#endregion


#region detect whether the specified directory is empty


<summary>


Detects whether the specified directory is empty


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


public static bool Isemptydirectory (string directorypath)


{


Try


{


To determine if a file exists


string[] FileNames = GetFileNames (DirectoryPath);


if (Filenames.length > 0)


{


return false;


}


Determine if a folder exists


string[] Directorynames = GetDirectories (DirectoryPath);


if (Directorynames.length > 0)


{


return false;


}


return true;


}


catch (Exception ex)


{


Loghelper.writetracelog (Traceloglevel.error, ex. message);


return true;


}


}


#endregion


#region detect if the specified file exists in the specified directory


<summary>


Detects if a specified file exists in the specified directory, use an overloaded method to search for subdirectories.


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


<param name= "searchpattern" > Pattern string, "*" stands for 0 or n characters, "?" Represents 1 characters.


Example: "Log*.xml" means searching all XML files that start with Log. </param>


public static bool Contains (string directorypath, String searchpattern)


{


Try


{


Gets the specified list of files


string[] FileNames = GetFileNames (DirectoryPath, searchpattern, false);


Determine if the specified file exists


if (filenames.length = 0)


{


return false;


}


Else


{


return true;


}


}


catch (Exception ex)


{


Loghelper.writetracelog (Traceloglevel.error, ex. message);


return false;


}


}


<summary>


Detects if a specified file exists in the specified directory


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


<param name= "searchpattern" > Pattern string, "*" stands for 0 or n characters, "?" Represents 1 characters.


Example: "Log*.xml" means searching all XML files that start with Log. </param>


<param name= "Issearchchild" > whether to search subdirectories </param>


public static bool Contains (string directorypath, String searchpattern, bool issearchchild)


{


Try


{


Gets the specified list of files


string[] FileNames = GetFileNames (DirectoryPath, searchpattern, true);


Determine if the specified file exists


if (filenames.length = 0)


{


return false;


}


Else


{


return true;


}


}


catch (Exception ex)


{


Loghelper.writetracelog (Traceloglevel.error, ex. message);


return false;


}


}


#endregion


#region Create a directory


<summary>


Create a Directory


</summary>


Absolute path </param> of <param name= "DirectoryPath" > Directory


public static void CreateDirectory (String directorypath)


{


Create the directory if the directory does not exist


if (! Isexistdirectory (DirectoryPath))


{


Directory.CreateDirectory (DirectoryPath);


}


}


#endregion


#region Create a file


<summary>


Create a file.


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static void CreateFile (String filePath)


{


Try


{


Create the file if it does not exist


if (! Isexistfile (FilePath))


{


Create a FileInfo object


FileInfo file = new FileInfo (FilePath);


Create a file


FileStream fs = file. Create ();


Close file stream


Fs. Close ();


}


}


catch (Exception ex)


{


Loghelper.writetracelog (Traceloglevel.error, ex. message);


Throw ex;


}


}


<summary>


Creates a file and writes a stream of bytes to the file.


</summary>


<param name= The absolute path of "FilePath" > Files </param>


<param name= "buffer" > Binary stream data </param>


public static void CreateFile (String filePath, byte[] buffer)


{


Try


{


Create the file if it does not exist


if (! Isexistfile (FilePath))


{


Create a FileInfo object


FileInfo file = new FileInfo (FilePath);


Create a file


FileStream fs = file. Create ();


Write binary stream


Fs. Write (buffer, 0, buffer.) Length);


Close file stream


Fs. Close ();


}


}


catch (Exception ex)


{


Loghelper.writetracelog (Traceloglevel.error, ex. message);


Throw ex;


}


}


#endregion


#region get the number of rows in a text file


<summary>


Get the number of lines in a text file


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static int Getlinecount (string filePath)


{


Reads the lines of a text file into an array of strings


string[] rows = File.ReadAllLines (FilePath);


return number of rows


return rows. Length;


}


#endregion


#region get the length of a file


<summary>


Gets the length of a file, in bytes


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static int GetFileSize (string filePath)


{


Create a File object


FileInfo fi = new FileInfo (FilePath);


Get the size of a file


return (int) fi. Length;


}


<summary>


Gets the length of a file in kilobytes


</summary>


<param name= "FilePath" > File path </param>


public static double getfilesizebykb (string filePath)


{


Create a File object


FileInfo fi = new FileInfo (FilePath);


Get the size of a file


Return converthelper.todouble (converthelper.todouble, FI. Length)/1024, 1);


}


<summary>


Gets the length of a file in megabytes (MB)


</summary>


<param name= "FilePath" > File path </param>


public static double Getfilesizebymb (string filePath)


{


Create a File object


FileInfo fi = new FileInfo (FilePath);


Get the size of a file


Return converthelper.todouble (converthelper.todouble, FI. Length)/1024/1024, 1);


}


#endregion


#region get a list of files in the specified directory


<summary>


Gets a list of all the files in the specified directory


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


public static string[] GetFileNames (string directorypath)


{


Throws an exception if the directory does not exist


if (! Isexistdirectory (DirectoryPath))


{


throw new FileNotFoundException ();


}


Get file List


Return Directory.GetFiles (DirectoryPath);


}


<summary>


Gets a list of all the files in the specified directory and subdirectories


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


<param name= "searchpattern" > Pattern string, "*" stands for 0 or n characters, "?" Represents 1 characters.


Example: "Log*.xml" means searching all XML files that start with Log. </param>


<param name= "Issearchchild" > whether to search subdirectories </param>


public static string[] GetFileNames (String directorypath, String searchpattern, bool issearchchild)


{


Throws an exception if the directory does not exist


if (! Isexistdirectory (DirectoryPath))


{


throw new FileNotFoundException ();


}


Try


{


if (issearchchild)


{


Return Directory.GetFiles (DirectoryPath, searchpattern, searchoption.alldirectories);


}


Else


{


Return Directory.GetFiles (DirectoryPath, searchpattern, searchoption.topdirectoryonly);


}


}


catch (IOException ex)


{


Throw ex;


}


}


#endregion


#region get a list of subdirectories in the specified directory


<summary>


Gets a list of all subdirectories in the specified directory, and to search for nested subdirectories, use the overloaded method.


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


public static string[] GetDirectories (string directorypath)


{


Try


{


Return directory.getdirectories (DirectoryPath);


}


catch (IOException ex)


{


Throw ex;


}


}


<summary>


Gets a list of all subdirectories in the specified directory and subdirectories


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


<param name= "searchpattern" > Pattern string, "*" stands for 0 or n characters, "?" Represents 1 characters.


Example: "Log*.xml" means searching all XML files that start with Log. </param>


<param name= "Issearchchild" > whether to search subdirectories </param>


public static string[] GetDirectories (String directorypath, String searchpattern, bool issearchchild)


{


Try


{


if (issearchchild)


{


Return Directory.getdirectories (DirectoryPath, searchpattern, searchoption.alldirectories);


}


Else


{


Return Directory.getdirectories (DirectoryPath, searchpattern, searchoption.topdirectoryonly);


}


}


catch (IOException ex)


{


Throw ex;


}


}


#endregion


#region write content to a text file


<summary>


Writing to a text file


</summary>


<param name= The absolute path of "FilePath" > Files </param>


<param name= "Content" > Writing </param>


public static void WriteText (string filePath, string content)


{


Write content to a file


File.writealltext (FilePath, content);


}


#endregion


#region Append to the tail of a text file


<summary>


Append to the tail of a text file


</summary>


<param name= The absolute path of "FilePath" > Files </param>


<param name= "Content" > Writing </param>


public static void AppendText (string filePath, string content)


{


File.appendalltext (FilePath, content);


}


#endregion


#region Copy the contents of an existing file into a new file


<summary>


Copy the contents of the source file to the destination file


</summary>


<param name= "Sourcefilepath" > Absolute path of source file </param>


<param name= "Destfilepath" > Target file absolute path </param>


public static void Copy (String sourcefilepath, String destfilepath)


{


File.Copy (Sourcefilepath, Destfilepath, true);


}


#endregion


#region move a file to a specified directory


<summary>


Move a file to a specified directory


</summary>


<param name= "Sourcefilepath" > Absolute path of the source file to be moved </param>


<param name= The absolute path of the directory to which "Descdirectorypath" > is moved </param>


public static void Move (string sourcefilepath,string descdirectorypath)


{


Get the name of the source file


String sourcefilename = GetFileName (Sourcefilepath);


if (Isexistdirectory (Descdirectorypath))


{


If a file with the same name exists in the target, delete the


if (Isexistfile (Descdirectorypath + "" + sourceFileName))


{


DeleteFile (Descdirectorypath + "" + sourceFileName);


}


Move a file to a specified directory


File.move (Sourcefilepath, Descdirectorypath + "" + sourceFileName);


}


}


#endregion


#region reads the stream into the buffer


<summary>


Read the stream to the buffer


</summary>


<param name= "Stream" > Original flow </param>


public static byte[] Streamtobytes (Stream stream)


{


Try


{


Create buffer


byte[] buffer = new Byte[stream. Length];


Read stream


Stream. Read (buffer, 0, Converthelper.toint32 (stream). Length));


return stream


return buffer;


}


catch (Exception ex)


{


Loghelper.writetracelog (Traceloglevel.error, ex. message);


Throw ex;


}


Finally


{


Close the stream


Stream. Close ();


}


}


#endregion


#region read the file to the buffer


<summary>


Read the file to the buffer


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static byte[] Filetobytes (string filePath)


{


Get the size of a file


int fileSize = GetFileSize (FilePath);


Create a temporary buffer


byte[] buffer = new Byte[filesize];


Create a file stream


FileInfo fi = new FileInfo (FilePath);


FileStream fs = fi. Open (FileMode.Open);


Try


{


Read the file stream into the buffer


Fs. Read (buffer, 0, fileSize);


return buffer;


}


catch (IOException ex)


{


Loghelper.writetracelog (Traceloglevel.error, ex. message);


Throw ex;


}


Finally


{


Close file stream


Fs. Close ();


}


}


#endregion


#region read a file to a string


<summary>


Read a file to a string


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static string Filetostring (String filePath)


{


Return filetostring (FilePath, baseinfo.defaultencoding);


}


<summary>


Read a file to a string


</summary>


<param name= The absolute path of "FilePath" > Files </param>


<param name= "Encoding" > Character encoding </param>


public static string Filetostring (String filepath,encoding Encoding)


{


Create a Stream reader


StreamReader reader = new StreamReader (filePath, encoding);


Try


{


Read stream


Return reader. ReadToEnd ();


}


catch (Exception ex)


{


Loghelper.writetracelog (Traceloglevel.error, ex. message);


Throw ex;


}


Finally


{


Turn off Stream reader


Reader. Close ();


}


}


#endregion


#region Get the file name (including extension) from the absolute path of the file


<summary>


Gets the file name (including extension) from the absolute path of the file


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static string GetFileName (String filePath)


{


Get the name of the file


FileInfo fi = new FileInfo (FilePath);


return FI. Name;


}


#endregion


#region Get the file name (without extension) from the absolute path of the file


<summary>


Gets the file name from the absolute path of the file (does not contain the extension)


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static string Getfilenamenoextension (String filePath)


{


Get the name of the file


FileInfo fi = new FileInfo (FilePath);


return FI. Name.split ('. ') [0];


}


#endregion


#region get an extension from the absolute path of the file


<summary>


Get an extension from the absolute path of a file


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static string GetExtension (String filePath)


{


Get the name of the file


FileInfo fi = new FileInfo (FilePath);


return FI. Extension;


}


#endregion


#region Empty The specified directory


<summary>


Clears all files and subdirectories in the specified directory, but the directory is still saved.


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


public static void Cleardirectory (String directorypath)


{


if (Isexistdirectory (DirectoryPath))


{


Delete all files in the directory


string[] FileNames = GetFileNames (DirectoryPath);


for (int i = 0; i < filenames.length; i++)


{


DeleteFile (Filenames[i]);


}


Delete all subdirectories in the directory


string[] Directorynames = GetDirectories (DirectoryPath);


for (int i = 0; i < directorynames.length; i++)


{


DeleteDirectory (Directorynames[i]);


}


}


}


#endregion


#region Empty the contents of a file


<summary>


Empty file contents


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static void Clearfile (String filePath)


{


deleting files


File.delete (FilePath);


Recreate the file


CreateFile (FilePath);


}


#endregion


#region Delete the specified file


<summary>


Delete the specified file


</summary>


<param name= The absolute path of "FilePath" > Files </param>


public static void DeleteFile (String filePath)


{


if (Isexistfile (FilePath))


{


File.delete (FilePath);


}


}


#endregion


#region Delete the specified directory


<summary>


Deletes the specified directory and all of its subdirectories


</summary>


<param name= "DirectoryPath" > Specify the absolute path of the directory </param>


public static void DeleteDirectory (String directorypath)


{


if (Isexistdirectory (DirectoryPath))


{


Directory.delete (DirectoryPath, true);


}


}


#endregion


}


}

File Class Two

The file path to create
public void CreateFolder (string folderpathname)
{
if (Folderpathname.trim (). Length> 0)
{
Try
{
String Createpath = System.Web.HttpContext.Current.Server.MapPath

(".. /.. /.. /images/"+folderpathname). ToString ();
if (! Directory.Exists (Createpath))
{
Directory.CreateDirectory (Createpath);
}
}
Catch
{
Throw
}
}
}

/**////
Delete the word folders and files under a folder
///
///
public void Deletechildfolder (string folderpathname)
{
if (Folderpathname.trim (). Length> 0)
{
Try
{
String Createpath = System.Web.HttpContext.Current.Server.MapPath

(folderpathname). ToString ();
if (directory.exists (Createpath))
{
Directory.delete (createpath,true);
}
}
Catch
{
Throw
}
}
}

/**////
Delete a file
///
///
public void DeleteFile (string filepathname)
{
Try
{
FileInfo delefile = new FileInfo (System.Web.HttpContext.Current.Server.MapPath

(Filepathname). ToString ());
Delefile.delete ();
}
Catch
{
}
}
public void CreateFile (string filepathname)
{
Try
{
Create a folder
String[] strpath= filepathname.split ('/');
CreateFolder (Filepathname.replace ("/" + strpath[strpath.length-1). ToString (), "")); Create a file

Clip
FileInfo CreateFile =new FileInfo (System.Web.HttpContext.Current.Server.MapPath

(Filepathname). ToString ()); Create a file
if (! createfile.exists)
{
FileStream fs=createfile.create ();
Fs. Close ();
}
}
Catch
{
}
}
/**////
Delete an entire folder and its Word folders and files
///
///
public void Deleparentfolder (string folderpathname)
{
Try
{
DirectoryInfo delfolder = new DirectoryInfo (System.Web.HttpContext.Current.Server.MapPath

(folderpathname). ToString ());
if (delfolder.exists)
{
Delfolder.delete ();
}
}
Catch
{
}
}
/**////
Append content to File
///
///
public void Rewritereadinnertext (String filepathname,string writeword)
{
Try
{
Creating folders and Files
CreateFolder (filepathname);
CreateFile (filepathname);
Get the contents of the original file
FileStream fileread=new FileStream (System.Web.HttpContext.Current.Server.MapPath

(Filepathname). ToString (), filemode.open,fileaccess.readwrite);
StreamReader filereadword=new StreamReader (Fileread,system.text.encoding.default);
String oldstring = Filereadword.readtoend (). ToString ();
oldstring = oldstring + Writeword;
Re-write new content to
StreamWriter Filewrite=new StreamWriter (Fileread,system.text.encoding.default);
Filewrite.write (Writeword);
Shut down
Filewrite.close ();
Filereadword.close ();
Fileread.close ();
}
Catch
{
Throw
}
}

/**////
Append content to File
///
///
public string Readerfiledata (string filepathname)
{
Try
{

FileStream fileread=new FileStream (System.Web.HttpContext.Current.Server.MapPath

(Filepathname). ToString (), filemode.open,fileaccess.read);
StreamReader filereadword=new StreamReader (Fileread,system.text.encoding.default);
String txtstring = Filereadword.readtoend (). ToString ();
Shut down
Filereadword.close ();
Fileread.close ();
return txtstring;
}
Catch
{
Throw
}
}
/**////
Read files for a folder
///
///
///
Public DirectoryInfo Checkvalidsessionpath (string filepathname)
{
Try
{
DirectoryInfo maindir = new DirectoryInfo (System.Web.HttpContext.Current.Server.MapPath

(Filepathname));
return maindir;

}
Catch
{
Throw
}
}
}
}

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.