简体   繁体   English

在C#中读取txt文件时,如何在文件目录中上一层?

[英]How to go one level higher in the file directory when reading a txt file in C#?

I have a txt file located in the application folder, in visual studio i just write "File.read("doc.txt")", however i would like to place the txt file outside of the applications folder 我在应用程序文件夹中有一个txt文件,在Visual Studio中,我只写了“ File.read(” doc.txt“)”,但是我想将txt文件放在应用程序文件夹之外

eg right now its located in c:\\Desktop\\Folder\\application\\doc.txt and i want to place the doc.txt inside c:\\desktop\\folder and read it from there without specifying the exact path of the txt file as folder might be moved to another drive eg inside D drive D:\\desktop\\folder 例如,现在它位于c:\\Desktop\\Folder\\application\\doc.txt ,我想将doc.txt放入c:\\desktop\\folder并从那里读取它,而没有将txt文件的确切路径指定为文件夹可能会移动到另一个驱动器,例如D驱动器D:\\desktop\\folder

if the user moves the folder and my hard code is "file.read("C:\\desktop\\folder\\doc.txt")" its going to throw an error, so how is there anyway to read a file that is one location above the applications main Folder? 如果用户移动了文件夹,而我的硬代码是“ file.read(“ C:\\ desktop \\ folder \\ doc.txt”)”,它将抛出一个错误,那么无论如何,如何读取一个位置的文件在应用程序主文件夹上方?

File.Read(@"..\doc.txt");

Will achieve this, the reason to add @ at the start is to show that you're writing a string literal which will allow you to use '\\' without needing to escape it. 可以做到这一点,在开始添加@的原因是表明您正在编写一个字符串文字,它将允许您使用'\\'而不需要对其进行转义。 the ".." part is how you tell the document to go into the parent directory. “ ..”部分是如何告诉文档进入父目录。

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

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