StreamReader的一个相对文件路径路径、文件、StreamReader

2023-09-04 09:59:55 作者:ι.石先生 丶

我想知道是否有人能告诉我怎么点一个StreamReader到程序的当前工作目录中的文件。

I was wondering if anyone could tell me how to point a StreamReader to a file inside the current working directory of the program.

例如。说我有prog程序,保存在目录C:\ ProgDir。我承诺\ ProgDir到共享文件夹。里面ProgDir是包含文件的其他目录中,我想导入到PROG(如\ ProgDir \ TESTDIR \ TESTFILE.TXT)我想让这个给StreamReader可以读取这些TestFiles,即使目录路径有改变;

E.G. Say I have program Prog, saved in the directory C:\ProgDir. I commit \ProgDir to a shared folder. Inside ProgDir is another directory containing files I'd like to import into Prog (e.g. \ProgDir\TestDir\TestFile.txt) I'd like to make it so that the StreamReader could read those TestFiles, even when the path to the directory has changed;

(如我的电脑上,在路径Testfiles是

(E.G., on my computer, the path to the Testfiles is

C:\ ProgDir \ TESTDIR \ TESTFILE.TXT

C:\ProgDir\TestDir\TestFile.txt

但其他人的计算机上,该目录是

but on the other person's computer, the directory is

C:\ DEV_ code \ ProgDir \ TESTDIR \ TESTFILE.TXT

C:\dev_code\ProgDir\TestDir\TestFile.txt

)。

我该如何获得一个StreamReader是强麦从TESTFILE.TXT阅读其他人的电脑上? (澄清,文件名不改变,唯一的变化是路径ProgDir)

How would I get a StreamReader to be ale to read from TestFile.txt on the other person's computer? (to clarify, the filenames do not change, the only change is the path ProgDir)

我试过如下:

string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(currentDir);
FileInfo file = new FileInfo(TestFile.txt);

string fullDirectory = directory.FullName;
string fullFile = file.FullName;

StreamReader sr = new StreamReader(@fullDirectory + fullFile);

(拉这个来自:Getting相对于当前的工作路径?)的

但我发现了TESTFILE不会在当前的背景下存在。任何人有任何想法,我应该如何处理这个?

But I'm getting "TestFile does not exist in the current context". Anyone have any idea as to how I should approach this?

感谢你。

推荐答案

是文件夹TESTDIR总是在可执行文件的目录? 如果是的话,试试这个

Is the Folder "TestDir" always in the executable directory? if so, try this

    string dir =System.IO.Path.GetDirectoryName(
      System.Reflection.Assembly.GetExecutingAssembly().Location);

    string file = dir + @"\TestDir\TestFile.txt";

这会给你的exe文件的路径加上里面的文件夹和文本文件

This will give you the path of the exe plus the folder inside it and the textfile