vb.net 在 File.Copy 期间找不到路径的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17461085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:08:32  来源:igfitidea点击:

Could not find a part of the path during File.Copy

vb.netfile-copying

提问by Artemis

I'm trying to copy a file to another directory but I'm getting this error

我正在尝试将文件复制到另一个目录,但出现此错误

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Documents and Settings\(my username)\Desktop\Source_Folder\File_1.xlsx'.

System.IO.DirectoryNotFoundException:找不到路径“C:\Documents and Settings\(我的用户名)\Desktop\Source_Folder\File_1.xlsx”的一部分。

But File_1.xlsx exists in the folder Source_Folder which exists on my Desktop. So why am I getting this error?

但是 File_1.xlsx 存在于我桌面上的 Source_Folder 文件夹中。那么为什么我会收到这个错误呢?

Here is my code

这是我的代码

    Dim path_orig As String = "C:\Documents and Settings\(my username)\Desktop\Source_Folder\"
    Dim oldFile As String = System.IO.Path.Combine(path_orig, filename)
    Dim path_new As String = Server.MapPath("~") & "\Destination_Folder\"
    Dim newFile As String = System.IO.Path.Combine(path_new, filename)
    File.Copy(oldFile, newFile, True)

*filename is a variable which in this case is "File_1.xlsx"

*filename 是一个变量,在这种情况下是“File_1.xlsx”

回答by Samuel Neff

Don't hard code Documents and Settings. It will change by OS. Use this instead:

不要硬编码Documents and Settings。它会因操作系统而改变。改用这个:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Source_Folder")

Also if you're running this in a web application you're likely running into permissions problems. Change the location where you're storing files and/or change the user the app pool is running under and/or grant the app pool user rights to the folder.

此外,如果您在 Web 应用程序中运行它,您可能会遇到权限问题。更改您存储文件的位置和/或更改运行应用程序池的用户和/或授予应用程序池用户对该文件夹的权限。