简体   繁体   English

通过传入绝对文件路径打开文件

[英]Opening a file by passing in absolute file path

I'm currently storing a file path for a file I would like to open and read in for my program. 我目前正在存储一个文件路径,该文件路径是我要打开并阅读程序的文件。 However when I put that path into File.OpenText it adds the path to the current directory to the file path and then I get this error: 但是,当我将该路径放入File.OpenText时,它将当前目录的路径添加到文件路径中,然后出现此错误:

DirectoryNotFoundException: Could not find a part of the path "/Users/km/Desktop/MP/file:/Users/km/Downloads/PT07E.obj".

The path I want is the one I am passing in, which is file:/Users/km/Downloads/PT07E.obj". 我想要的路径是我要传递的路径,即文件:/Users/km/Downloads/PT07E.obj”。

Is there a way to stop File.OpenText from adding to this path I am passing in originally? 有没有办法阻止File.OpenText添加到我最初传递的此路径中?

You have to add a correct absolute path - that means, you forgot to define the drive (normally it's C ). 您必须添加正确的绝对路径-这意味着您忘记定义驱动器(通常为C )。 So your path would have to be (I'd use backslashes): 因此,您的路径必须是(我将使用反斜杠):

@"C:\Users\km\Downloads\PT07E.obj"

However it's a better idea not to use an absolute path for this. 但是,最好不要为此使用绝对路径。 I'd use the specialFolder option of c#: 我会使用c#的specialFolder选项:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downlads", "PT07E.obj");

And it's always a good idea to use Path.Combine , that uses the standard path splitter of the OS. 使用Path.Combine总是一个好主意,它使用操作系统的标准路径分配器。

If you are operating with paths like file:/{absolute path} (which is actually an URI ) you may use System.Uri class. 如果您使用诸如file:/{absolute path} (实际上是URI )之类的file:/{absolute path} ,则可以使用System.Uri类。
As in this answer . 就像这个答案

var uri = new Uri("file:/Users/km/Downloads/PT07E.obj");
using (var reader = File.OpenText(uri.AbsolutePath))
{
   ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM