C#中常用的文件及目錄操作功能
C#中常用的文件及目錄操作功能
/建立新檔案
private static void CreateFile(string fileName)
{
FileStream fs = File.Create(fileName);
fs.Close();
}
//讀檔案
private static string ReadFile(string fileName)
{
string content = “”;
content = File.ReadAllText(fileName);
return content;
}
//刪除檔案
private static void DeleteFile(string fileName)
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
//複製檔案
private static void CopyFile(string sourceFileName, string destFileName)
{
if (File.Exists(sourceFileName))
{
File.Copy(sourceFileName, destFileName);
}
}
//移動檔案
private static void MoveFile(string sourceFileName, string destFileName)
{
if (File.Exists(sourceFileName))
{
File.Move(sourceFileName, destFileName);
}
}
//建立目錄
private static void CreateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
//刪除目錄,recursive為True時,直接刪除目錄及其目錄下所有文件或子目錄;recursive為False時,需先將目錄下所有文件或子目錄刪除
private static void DeleteDirectory(string path, bool recursive)
{
if (Directory.Exists(path))
{
if (recursive)
{
Directory.Delete(path, true);
}
else
{
Console.WriteLine(“Please delete the files or sub directory first!”);
}
}
}
//移動目錄
private static void MoveDirectory(string sourceDirName, string destDirName)
{
if (Directory.Exists(sourceDirName))
{
Directory.Move(sourceDirName, destDirName);
}
}
//讀取目錄下所有子目錄(條列所有子目錄)
private static ArrayList GetDirectories(string path)
{
ArrayList directories = new ArrayList();
if (Directory.Exists(path))
{
directories.AddRange(Directory.GetDirectories(path));
}
return directories;
}
//讀取目錄下所有檔案(單一層,沒有遞迴)
private static ArrayList GetFiles(string path)
{
ArrayList files = new ArrayList();
if (Directory.Exists(path))
{
files.AddRange(Directory.GetFiles(path));
}
return files;
}