在C#(.NET 2.0)中重命名文件,而无需移动文件或使用DOS / Visual Basic命令。

10 浏览
0 Comments

在C#(.NET 2.0)中重命名文件,而无需移动文件或使用DOS / Visual Basic命令。

我还没有在.NET的C#中找到一个文件重命名函数,所以我有点困惑我应该如何重命名一个文件。我使用命令提示符和Process.Start,但这并不是很专业,而且每次都会弹出一个黑色的DOS窗口。是的,我知道在Visual Basic命名空间中有些东西,但我不打算将\"visual-basic.dll\"添加到我的项目中。\n我找到了一些将文件\"移动\"来重命名它的示例。这是一种相当痛苦的方法,也是一个拙劣的变通方法。这样的操作我可以自己编程。\n每种语言都有重命名命令,所以我很惊讶C#没有或者我还没有找到。哪个是正确的命令?\n对于大文件和在光盘上重命名,这段代码可以工作,但你的项目将部分转换为Visual Basic(据我理解,也许不是这样):\n

//在项目中添加Microsoft.VisualBasic.MyServices引用和命名空间;
//对于目录:
 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;
     } //只是让Visual Studio的错误生成器闭嘴
 }
 //对于文件:
 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;
     } //只是让Visual Studio的错误生成器闭嘴
 }

0
0 Comments

在C#(.NET 2.0)中重命名文件(不移动文件或使用DOS / Visual Basic命令)的问题是由于重命名实际上是移动文件的操作,而操作系统对于这两种操作的内部实现方式是相同的。在资源管理器中,同一分区上的移动操作几乎是瞬时完成的,它只是调整文件名和逻辑位置。要在同一目录中重命名文件,只需将其移动到同一目录下的新文件名即可。

以下是解决该问题的C#代码示例:

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());
        }
    }
}

在该示例代码中,首先检查源文件是否存在,如果不存在,则创建一个文件。然后检查目标文件是否存在,如果存在,则删除目标文件。最后,使用`File.Move`方法将源文件移动到目标文件的位置。移动完成后,判断源文件是否仍然存在,如果存在则输出“原始文件仍然存在”,如果不存在则输出“原始文件不存在”。

0