C# 对文件与文件夹的操作删除、移动与复制
2012-11-14 15:25:09 来源:WEB开发网{
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);
}
}
更多精彩
赞助商链接