[英]Rename a file in C# (NET 2.0) without moving it or using DOS / Visual Basic commands
我還沒有在C#的.NET中找到文件重命名功能,因此我對如何重命名文件有些困惑。 我在Process.Start中使用命令提示符,但這並不是很專業,每次都彈出一個黑色的DOS窗口。 是的,我知道Visual Basic命名空間中有某些內容,但這並不是我要將“ visual-basic.dll”添加到我的項目中的意圖。
我找到了一些“移動”文件以對其重命名的示例。 這是一種非常痛苦的方法,並且是解決問題的偽劣解決方案。 這樣的步法我可以自己編程。
每種語言都有重命名命令,因此令我驚訝的是C#尚未或尚未發現。 什么是正確的命令?
對於大文件並在CD上重命名,此代碼有效,但您的項目將部分轉換為Visual Basic(據我了解,也許並非如此):
//Add the Microsoft.VisualBasic.MyServices reference and namespace in a project;
//For directories:
private static bool RenameDirectory(string DirPath, string NewName)
{
try
{
FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
FileSystem.RenameDirectory(DirPath, NewName);
FileSystem = null;
return true;
}
catch {
return false;
} //Just shut up the error generator of Visual Studio
}
//For files:
private static bool RenameFile(string FilePath, string NewName)
{
try
{
FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
FileSystem.RenameFile(FilePath, NewName);
FileSystem = null;
return true;
}
catch {
return false;
} //Just shut up the error generator of Visual Studio
}
重命名只是一招,反之亦然,請參閱MSDN: File.Move
在OS中,對於所有目的而言,操作都是相同的。 這就是在資源管理器中幾乎立即在同一分區上移動的原因-只需調整文件名和邏輯位置即可。 要重命名同一目錄中的文件,請將其移至同一目錄中的新文件名。
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
string path2 = @"c:\temp2\MyTest.txt";
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
Console.WriteLine("{0} was moved/renamed to {1}.", path, path2);
// See if the original exists now.
if (File.Exists(path))
{
Console.WriteLine("The original file still exists, which is unexpected.");
}
else
{
Console.WriteLine("The original file no longer exists, which is expected.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.