C#我正在尝试将一个文件从一个我不知道文件名的目录移动到一个新目录
我在下面抛出了一个异常:System.ArgumentException:'空文件名是不合法的。 参数名称:sourceFileName'C#我正在尝试将一个文件从一个我不知道文件名的目录移动到一个新目录,c#,file,directory,C#,File,Directory,我在下面抛出了一个异常:System.ArgumentException:'空文件名是不合法的。 参数名称:sourceFileName' public bool ArchiveFile() { int fileCount = Directory.GetFiles(@"\\company\Archive\IN\InvoiceTest\Inbox\").Length; DirectoryInfo diFileCheck = new Directory
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;
}
}
你的问题是:
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
请参见这将读取源目录中的所有文件,并将其移动到目标目录:
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
}
如果没有文件名,您希望发生什么?如果有人沉默地回答“Wich file?”这个问题,你会有什么合乎逻辑的事情发生?我在哪里定义文件名?谢谢你的提示。这给了我不可开票的成员FileInfo。名称不能像方法一样使用。@Joe您需要将其用作属性,例如字符串strSourceFile=fi.Name;啊,是的!谢谢在File.Move行中,我得到“找不到文件C:\dev”有一个google和更新的NuGet软件包,但它仍然存在showing@Joe您需要将文件名附加到您正在枚举的原始目录路径。不过我认为这是我的问题,我可以附加文件名,但我希望能够从原始目录中提取任何.csv文件,因为我可能不知道未来的文件名-这可能吗?