[英]Move a file from one directory to another
我用DotNetZip创建了一个zip文件/文件夹。 我正在尝试将该文件从原始目录/文件夹移动到另一个文件,例如My Documents。 到目前为止,我已经完成了以下操作,但它给了我一个错误,说它无法找到路径的一部分。
private static void Move()
{
try
{
Directory.Move(@"Debug\Settings.zip", IO.Paths.Enviroment.MyDocuments);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
更新:所以我玩了一下并笑了,不是因为我修理了它,而是因为它很奇怪。 我使用了File.Move()
和Directory.Move()
并更改了both.Move(@"Debug\\Settings.zip",...);
to both.Move(@"Settings.zip",...);
然后得到一个错误说Cannot create a file when that file already exists.
虽然使用Directory.Move
来移动文件可能看起来很奇怪,但是(我使用File.Move
代替), Jean-Philippe Leclerc指出它会起作用。
问题是路径Debug\\Settings.zip
:
所有相对路径都相对于工作目录。 默认情况下,工作目录是执行程序集(程序)的文件夹,以及调试时项目的bin\\Debug
子文件夹。 所以你的路径Debug\\Settings.zip
扩展到如下路径:
C:\..\MyProject\bin\Debug\Debug\Settings.zip
这可能不是你的意思。 你的意思是"Settings.zip"
。
事实上它是一个ZIP是无关紧要的。
could not find part of the path
- 错误似乎是文件Settings.Zip
的Relative Path
不是有效路径!
您需要使用File.Move
, Directory.Move
将Directory.Move
的整个内容移动到不同的文件夹。
File.Move
:仅将文件移动到指定位置
private static void Move()
{
try
{
File.Move(@"Debug\Settings.zip", System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
使用System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)获取MyDocuments路径。
固定! 问题首先是"Debug\\Settings.zip"
应该是"Settings.zip"
或@"Settings.zip"
,最后目的地不应该只是System.IO.File.Move(@"Settings.zip", System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop));
但是System.IO.File.Move(@"Settings.zip", System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + @"\\Settings.zip");
基本上,在目标字符串的末尾添加文件名和文件扩展名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.