WEB开发网
开发学院WEB开发ASP.NET C# 对文件与文件夹的操作删除、移动与复制 阅读

C# 对文件与文件夹的操作删除、移动与复制

 2012-11-14 15:25:09 来源:WEB开发网   
核心提示:if (file.Exists) { file.Delete(); } }下面的代码分别使用了Directory类和DirectoryInfo类来演示如何删除文件夹void DeleteFolder1() { string folderToBeDeleted = @"c:\temp\test"; i
if (file.Exists)
{
file.Delete();
}
}


下面的代码分别使用了Directory类和DirectoryInfo类来演示如何删除文件夹


void DeleteFolder1()
{
string folderToBeDeleted = @"c:\temp\test";
if (Directory.Exists(folderToBeDeleted))
{
// true is recursive delete:
Directory.Delete(folderToBeDeleted, true);
}
}


void DeleteFolder2()
{
string folderToBeDeleted = @"c:\temp\test";
DirectoryInfo folder = new DirectoryInfo(folderToBeDeleted);
if (folder.Exists)
{
folder.Delete(true);
}
}

下面的代码分别使用了File类和FileInfo类来演示如何移动文件


void MoveFile1()
{
string fileToMove = @"c:\temp\New Text Document.txt";
string fileNewDestination = @"c:\temp\test.txt";
if (File.Exists(fileToMove) && !File.Exists(fileNewDestination))
{
File.Move(fileToMove, fileNewDestination);
}
}

void MoveFile2()
{
string fileToMove = @"c:\temp\New Text Document.txt";
string fileNewDestination = @"c:\temp\test.txt";
FileInfo file = new FileInfo(fileToMove);
if (file.Exists)
{
file.MoveTo(fileNewDestination);
}
}

下面的代码分别使用了Directory类和DirectoryInfo类来演示如何移动文件夹


void MoveFolder1()
{
string folderToMove = @"c:\temp\test";
string folderNewDestination = @"c:\temp\test2";
if (Directory.Exists(folderToMove))
{
Directory.Move(folderToMove, folderNewDestination);
}
}


void MoveFolder2()
{
string folderToMove = @"c:\temp\test";
string folderNewDestination = @"c:\temp\test2";
DirectoryInfo folder = new DirectoryInfo(folderToMove);
if (folder.Exists)
{
folder.MoveTo(folderNewDestination);
}
}

下面的代码分别使用了File类和FileInfo类来演示如何复制文件


void CopyFile1()
{
string sourceFile = @"c:\temp\New Text Document.txt";
string destinationFile = @"c:\temp\test.txt";
if (File.Exists(sourceFile))
{
// true is overwrite
File.Copy(sourceFile, destinationFile, true);
}
}


void CopyFile2()
{
string sourceFile = @"c:\temp\New Text Document.txt";
string destinationFile = @"c:\temp\test.txt";
FileInfo file = new FileInfo(sourceFile);
if (file.Exists)
{
// true is overwrite
file.CopyTo(destinationFile, true);
}
}

上一页  1 2 

Tags:文件 文件夹 操作

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接