如何为流阅读器设置特定路径以从中打开文件。 [英] How Do I Set A Specific Path For Stream Reader To Open A File From.
问题描述
我需要打开包含DNA密码子的文件并将其读出到列表文件中。我很确定我把它弄下来但我无法测试它,因为我无法将文件路径重定向到我想要的。我已经使用了几种不同的技术来做到这一点,但没有一种方法可行。继续我当前的设置:
I need to open a file contain in DNA codons and read it out to a list file. Im pretty sure i got it down but i can't test it because i can't redirect the file path to what i want. I've used several different techniques to do this but none have worked. Heres my current setup:
private void btnOpen_Click(object sender, EventArgs e)
{
string DNA; //Declares a string variable named DNA
int Lines, Index;//Declares an integer named Lines
DNA = @"\documents\visual studio 2013\Projects\DNA\DNA.txt";
StreamReader DNAfile; //Declares a StreamReader Variable named DNAfile
DNAfile = File.OpenText(DNA); //opens the file "DNA.txt" as the DNAfile Variable
Lines = File.ReadLines("DNA.txt").Count(); //Counts the number of lines in the DNA.txt file and sets it equal to the integer "Lines"
string[] DNAarray = new string[Lines]; //Creates an string array with the length of the number of lines in the file "DNA.txt"
Index = 0;
while (Index < DNAarray.Length && !DNAfile.EndOfStream)
{
DNAarray[Index] = DNAfile.ReadLine();
Index++;
}
foreach (string value in DNAarray)
{
lstOut.Items.Add(DNAarray);
}
}
DNA字符串上的路径是正确的路径但我得到一个错误,说文件不能找到并且系统使用的路径是'\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\我把它换成了。我做错了什么?
the path on the DNA string is the correct path but i get an error saying the file can't be found and the path the system uses is '\\psf\home\documents\visual studio 2013\Projects\DNA\DNA\bin\Debug\DNA.txt' no matter what i change it to. What am i doing wrong?
推荐答案
你打开文件两次。首先使用 File.OpenText(DNA),然后使用 File.ReadLines(DNA.txt)。而后者抛出异常,因为你只指定了文件名,没有路径。
As File.ReadLines(..) [ ^ ]返回IEnumerable< string>将所有文本行包含为字符串,大部分其他代码都是不必要的。
如果lstOut
是ListBox,您甚至可以删除foreach循环并使用 ListBox.AddRange(..) [ ^ ]添加IEnumerable< string>中的所有字符串立刻(使用.ToArray())。
You open the file twice. First with File.OpenText(DNA), then with File.ReadLines("DNA.txt"). And the latter throws the exception because you only specified the file name, no path.
As File.ReadLines(..)[^] returns an IEnumerable<string> containing all the text-lines as strings, most of your other code is unneccessary.
IflstOut
is a ListBox, you can even remove the foreach-loop and use ListBox.AddRange(..)[^] to add all strings from the IEnumerable<string> at once (with .ToArray()).
这篇关于如何为流阅读器设置特定路径以从中打开文件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!