【问题标题】:Why isn't my File.Move() working?为什么我的 File.Move() 不工作?
【发布时间】:2010-06-17 00:59:02
【问题描述】:

我不确定我在这里到底做错了什么......但我注意到我的 File.Move() 没有重命名任何文件。
另外,有人知道在我的第二个循环中如何使用路径列表和经过清理的文件名填充我的 .txt 文件吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication2
{
class Program
{
    static void Main(string[] args)
    {

        //recurse through files.  Let user press 'ok' to move onto next step        
        string[] files = Directory.GetFiles(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
        foreach (string file in files)
        {
            Console.Write(file + "\r\n");
        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey(true);
        //End section

        //Regex -- find invalid chars
        string pattern = " *[\\~#%&*{}/<>?|\"-]+ *";
        string replacement = " ";
        Regex regEx = new Regex(pattern);

        string[] fileDrive = Directory.GetFiles(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
        List<string> filePath = new List<string>();

        //clean out file -- remove the path name so file name only shows
        string result;            
        foreach(string fileNames in fileDrive)
        {
        result = Path.GetFileName(fileNames);
        filePath.Add(result);

        }

        StreamWriter sw = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt");

        //Sanitize and remove invalid chars
        foreach(string Files2 in filePath)
        {
            try
            {
                string sanitized = regEx.Replace(Files2, replacement);
                sw.Write(sanitized + "\r\n");
                System.IO.File.Move(Files2, sanitized);
                System.IO.File.Delete(Files2);




            }
            catch (Exception ex)
            { 
            Console.Write(ex);
            }


        }
        sw.Close();

    }

}

}

我对 C# 非常陌生,并尝试编写一个通过特定驱动器递归的应用程序,找到无效字符(如 RegEx 模式中指定的那样),将它们从文件名中删除,然后编写一个 .txt 文件,该文件具有路径名和更正后的文件名。

有什么想法吗?

【问题讨论】:

  • 如果你是 C# 新手,千万不要在不处理异常的情况下执行 try/catch;您很可能忽略了解释问题所在的错误消息。
  • 非常适合新程序员。现在,看到那个空的catch { } 块了吗?这就是您看不到真正错误的原因!试试catch(Exception ex) { Console.Write(ex); }
  • 我在我所做的编辑中将异常处理添加到我的代码中。但是,我没有任何例外。正在写入的 .txt 仅更改 .txt 文件中的字符串——而不是文件本身。

标签: c# .net


【解决方案1】:

您的文件路径列表仅包含文件名称。您已在对Path.GetFileName() 的调用中删除了目录信息,因此您的 File.Move 正在应用程序的默认目录中查找目标文件,而不是其原始位置。

我认为您保存已清理文件名的代码是正确的。不过,您应该在 StreamWriter 周围使用 using() 构造,如下所示,以确保文件在完成后关闭。

//clean out file -- remove the path name so file name only shows
string result;            
foreach(string fileNames in fileDrive)
{
    // result = Path.GetFileName(fileNames); // don't do this.
    filePath.Add(fileNames);
}

using (StreamWriter sw = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt"))
{
        //Sanitize and remove invalid chars  
        foreach(string Files2 in filePath)  
        {  
            try  
            {  
                string filenameOnly = Path.GetFileName(Files2);
                string pathOnly = Path.GetDirectoryName(Files2);
                string sanitizedFilename = regEx.Replace(filenameOnly, replacement);
                string sanitized = Path.Combine(pathOnly, sanitizedFilename);  
                sw.Write(sanitized + "\r\n");  
                System.IO.File.Move(Files2, sanitized);  
            }  
            catch  
            {   
            }  
        }  
}

【讨论】:

  • 那么,我应该不使用 GetFileName() 而是将整个路径传递给 File.Move()?
  • 请确保您不会意外清理文件夹名称,否则您会收到错误消息,因为您将尝试将文件移动到不存在的“清理”文件夹(如果它有任何“无效”字符)。类似于File.Move(Path.Combine(folder, Files2), Path.Combine(folder. sanitized)) 的东西,其中folder 与您在上面使用的相同。
  • 我刚试过这个——但它实际上并没有重命名文件名。它在 .txt 文件中重命名它......但不是文​​件本身。有什么我可能错过的吗?
  • 你是否通过了整个路径?现在检查代码示例,看看你的进展如何。
  • 删除“删除(Files2)”行;它是多余的,从技术上讲,每次都应该引起异常;更不用说如果你的文件没有任何特殊字符是非常危险的。如果两个文件名相同,File.Move 不会执行任何操作,但您将删除原始文件!另外,请使用Console.WriteLine(ex.Message),并密切注意输出窗口是否有任何错误。自己写(前)实际上不会给你错误信息。编辑:嘿,发布太晚了 5 分钟 :)
【解决方案2】:

在调用 File.Move() 时是否引发了任何异常?您在其下方有一个空的捕获块,它将阻止您看到它们。尝试删除 catch{} 或在其中添加一些代码以记录任何异常。

【讨论】:

    【解决方案3】:

    尝试使用File.AppendAllLines()(带有集合)或File.AppendAllText()(对于每个单独的)而不是流。这会让事情变得容易一些。

    另外,我知道不希望您的应用程序被炸毁,但至少,当您当前正在编写/调试评论时,您的 try 会屏蔽,以便您可以看到异常。

    可能不是答案,但可能是一个可以提供帮助的建议。

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 2014-05-17
      • 2017-09-20
      • 2012-04-14
      • 2016-09-15
      • 2012-02-14
      • 2012-08-10
      • 2013-07-27
      • 1970-01-01
      相关资源
      最近更新 更多