【问题标题】:C# I am trying to move a file from one directory, where I wont know what the name of the file is, to a new directoryC# 我正在尝试将一个文件从一个我不知道文件名的目录移动到一个新目录
【发布时间】:2019-11-29 15:03:53
【问题描述】:

我有以下抛出异常: System.ArgumentException: '空文件名不合法。 参数名称:sourceFileName'

    public bool ArchiveFile()
    {
        int fileCount = Directory.GetFiles(@"\\company\Archive\IN\InvoiceTest\Inbox\").Length;
        DirectoryInfo diFileCheck = new DirectoryInfo(@"\\company\Archive\IN\InvoiceTest\Inbox\");
        foreach (var fi in diFileCheck.GetFiles())
        {
            string strSourceFile = Path.GetFileName(@"\\company\Archive\\IN\InvoiceTest\Inbox\");
            string strDestination =Path.Combine(@"\\company\ArchiveIN\InvoiceTest\Archive\", strSourceFile);
            File.Move(strSourceFile, strDestination);
        }
        if (fileCount==0)
        {
            string strMessage = "No file found in directory: \n\n";
            MessageBox.Show(strMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
        else 
        {
           return true;
        }
    }

【问题讨论】:

  • 如果没有文件名,您期望会发生什么?如果有人回答“Wich file?”这个问题,会发生什么合乎逻辑的事情?沉默?
  • 在哪里定义文件名?

标签: c# file directory


【解决方案1】:

你的问题在这里:

foreach (var fi in diFileCheck.GetFiles())
{
    string strSourceFile = Path.GetFileName(@"\\company\Archive\\IN\InvoiceTest\Inbox\");
    string strDestination = Path.Combine(@"\\company\ArchiveIN\InvoiceTest\Archive\", strSourceFile);
    File.Move(strSourceFile, strDestination);
}

您的fi 是一个FileInfo 对象,但您没有使用它。不要使用Path.GetFileName,而是使用fi.Name

FileInfo

【讨论】:

  • 感谢您的提示。这给了我不可调用的成员 FileInfo.Name 不能像方法一样使用。
  • @Joe 您需要将其用作属性,例如字符串 strSourceFile = fi.Name;
  • 啊,是的!谢谢!在 File.Move 行我得到'找不到文件 C:\dev' 有一个谷歌和更新的 NuGet 包,但它仍然显示
  • @Joe 您需要将文件名附加到您枚举的原始目录路径中。
  • 我认为那是我的问题,我可以附加文件名,但我希望能够从原始目录中获取任何 .csv 文件,因为我可能不知道以后的文件名 - 是这甚至可能吗?
【解决方案2】:

这会从源目录读取所有文件,并将它们移动到目标目录:

var filePaths = Directory.GetFiles("Source"); // get file paths from folder 'Source'

foreach (var filePath in filePaths)
{
    var fileName = Path.GetFileName(filePath); // get only the name of the file

    var targetPath = Path.Combine("Target", fileName); // create path to target directory 'Target' (including file name)

    File.Move(filePath, targetPath); // move file from source path to target path
}  

【讨论】:

    猜你喜欢
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多