繁体   English   中英

文件 ReadAllText 的路径错误(C#)

[英]File ReadAllText is getting a wrong path (C#)

我有一个本地项目,未来将在筹备中。 因此,我需要使用相对路径来获取和读取 json 文件。 但是使用File.ReadAllText我得到了以下答案:

> File.ReadAllText("MyJsonFiletoRead.json", Encoding.Default) 
System.IO.FileNotFoundException: Could not find file 'C:\Users\15071\MyJsonFiletoRead.json'

请注意,“C:\Users\15071”不是项目文件夹,这是我的 windows 用户文件夹。 我的结构在这里:

C:\Projetcs\MyProjectTest  -->> Project folder

C:\Projetcs\MyProjectTest\MyClass.cs  -->> The class where I'm calling the ReadAllText

C:\Projetcs\MyProjectTest\MyJsonFiletoRead.json -->> My json file that I'm trying to find

我尝试了以下命令来检查我的 PATH,但所有答案都是错误的:

> Environment.CurrentDirectory
 "C:\\Users\\15071"

> Directory.GetCurrentDirectory()
 "C:\\Users\\15071"

AppDomain.CurrentDomain.BaseDirectory
"c:\\program files (x86)\\microsoft visual studio\\2019\\community\\common7\\ide\\commonextensions\\microsoft\\managedlanguages\\vbcsharp\\languageservices\\DesktopHost\\"

有没有人解决这个问题?

注意:如果我使用完整路径,它可以工作:

File.ReadAllText("C:/Projetcs/MyProjectTest/MyJsonFiletoRead.json", Encoding.Default)

如果该文件位于可执行文件的同一文件夹中,则只需传递文件名:

File.ReadAllText("MyJsonFiletoRead.json", Encoding.Default); 

如果该文件位于可执行文件所在文件夹的相对路径中,则可以获取程序集位置并将其与相对路径组合:

var path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..\\..\\MyJsonFiletoRead.json");
File.ReadAllText(path, Encoding.Default);

您需要找到当前文件夹,然后读取文件

var currentFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)
File.ReadAllText(currentFolder + "/MyJsonFiletoRead.json")

暂无
暂无

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

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