新的C# - 无法获得File.Copy工作
这是微软的代码示例,用不同的文件位置,这是行不通的:新的C# - 无法获得File.Copy工作
string fileName = "test1.txt";
string sourcePath = @"C:\";
string targetPath = @"C:\Test\";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourceFile, destFile, true);
它不能找到源文件。如果我把一个破发点,这是我得到:
args {string[0]} string[]
fileName "test1.txt" string
sourcePath "C:\\" string
targetPath "C:\\Test\\" string
sourceFile "C:\\test1.txt" string
destFile "C:\\Test\\test1.txt" string
所以它看起来是加倍反斜杠即使使用原义字符串。 (毫无疑问,我在C中有一个test1.txt文件:)任何想法?谢谢!
加倍是正确的, 我觉得你的问题是文件名。 尝试读取没有该操作的文件,但在查看是否“隐藏已知类型的扩展名”(如果您的文件名应该是test1.txt.txt)之前,请先阅读此文件:
谢谢,并多谢了,那就是问题! – MariusD 2012-04-10 14:40:51
双反斜杠是在字符串中表示反斜杠的常用方法。当你使用@你是说你不想解释任何转义序列(除其他事项外,请参阅here获取更多信息,在“文字”下)
所以问题是不同的。是否存在C:\ test1.txt和C:\ Test?你有权限写入targetPath吗?
尝试以下操作(添加异常处理和更多的错误检查需要)
if (!Directory.Exists(targetPath)) {
Directory.CreateDirectory(targetPath);
}
if (File.Exists(sourceFile)) {
File.Copy(sourceFile,destFile,true);
}
有3种常见的故障模式:
- 源文件
C:\test1.txt
不存在。 - 目标文件
C:\Test\test1.txt
存在但是只读。 - 目标目录
C:\Test
不存在。
我的猜测是第3项是问题,如果是的话,您需要确保目标目录存在,然后再致电File.Copy
。如果是这种情况,你会看到一个DirectoryNotFoundException
。您可以使用Directory.CreateDirectory
来确保目标目录存在。
如果您有麻烦尝试,看看下面这个例子:
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
string path2 = path + "temp";
try
{
// Create the file and clean up handles.
using (FileStream fs = File.Create(path)) {}
// Ensure that the target does not exist.
File.Delete(path2);
// Copy the file.
File.Copy(path, path2);
Console.WriteLine("{0} copied to {1}", path, path2);
// Try to copy the same file again, which should succeed.
File.Copy(path, path2, true);
Console.WriteLine("The second Copy operation succeeded, which was expected.");
}
catch
{
Console.WriteLine("Double copy is not allowed, which was not expected.");
}
}
}
来自反斜线http://msdn.microsoft.com/en-us/library/system.io.file.copy(v=vs.71).aspx
要准确查看出了什么问题,在try-catch
块中的代码:
try { // Code that can throw an exception }
catch (Exception ex)
{
// Show what went wrong
// Use Console.Write() if you are using a console
MessageBox.Show(ex.Message, "Error!");
}
最有可能的问题是缺少的源文件,目标文件夹不存在,或者您没有权限访问该位置。
在Windows 7上,我注意到您需要管理员权限才能直接写入安装操作系统的驱动器的根目录(通常为c:\
)。 尝试编写文件或在该位置创建目录可能会失败,因此我建议您使用其他位置。
什么是异常消息和堆栈跟踪? – SLaks 2012-04-10 14:13:38
反斜杠加倍仅用于显示。你收到什么错误信息。 – 2012-04-10 14:13:46
您能否发布例外文本?双反斜杠很好。 – Matten 2012-04-10 14:14:21