2010年9月7日 星期二

C# 檔案,資料夾 Move Copy Del Insert

檔案複製

string sourcePath = @"C:\Users\Public\TestFolder";
string targetPath = @"C:\Users\Public\TestFolder\SubDir";
System.IO.File.Copy(sourceFile, destFile, true);


檔案搬移

System.IO.File.Move(sourceFile, destinationFile);


檔案刪除

if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
{
// Use a try block to catch IOExceptions, to
// handle the case of the file already being
// opened by another process.
try
{
System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}


建立資料夾

if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}



複製資料夾

if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);

// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}


搬移資料夾

System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");


刪除資料夾

if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest"))
{
try
{
System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true);
}

catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}


參考網站

沒有留言:

張貼留言