C#从文本文件读取,新行
我的代码写文本到一个文件的工作非常完美C#从文本文件读取,新行,c#,file-io,C#,File Io,我的代码写文本到一个文件的工作非常完美 string path = @"./prefs.dat"; string stringdir = textBox1.Text + Environment.NewLine + textBox2.Text + Environment.NewLine; System.IO.File.WriteAllText(path, stringdir); Process test = new Process(
string path = @"./prefs.dat";
string stringdir = textBox1.Text + Environment.NewLine + textBox2.Text + Environment.NewLine;
System.IO.File.WriteAllText(path, stringdir);
Process test = new Process();
string FileName = "prefs.dat";
StreamReader sr = new StreamReader(FileName);
List<string> lines = new List<string>();
lines.Add(sr.ReadLine());
string s = lines[0];
sr.Close();
test.StartInfo.FileName = s;
test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
test.StartInfo.CreateNoWindow = false;
test.Start();
然后从文件中读取,我使用这个代码,它再次完美地工作
string path = @"./prefs.dat";
string stringdir = textBox1.Text + Environment.NewLine + textBox2.Text + Environment.NewLine;
System.IO.File.WriteAllText(path, stringdir);
Process test = new Process();
string FileName = "prefs.dat";
StreamReader sr = new StreamReader(FileName);
List<string> lines = new List<string>();
lines.Add(sr.ReadLine());
string s = lines[0];
sr.Close();
test.StartInfo.FileName = s;
test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
test.StartInfo.CreateNoWindow = false;
test.Start();
然后它失败了,我得到一个空结果。当我进一步查看时,错误甚至看不到第二行,尽管我显然有两行。ReadLine()
方法一次读取一行,您需要使用while循环以以下方式添加所有行:
string line="";
while((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
string s = lines[1];
看
另一种方法是使用一次读取所有行,然后访问第二行:
string[] lines = System.IO.File.ReadAllLines(stringdir);
string s = lines[1];
如果您想将第二行的内容获取为
字符串s=lines[1],请参见代码>您需要先将其添加到列表中
Process test = new Process();
string FileName = "prefs.dat";
StreamReader sr = new StreamReader(FileName);
List<string> lines = new List<string>();
lines.Add(sr.ReadLine());
lines.Add(sr.ReadLine());
string s1 = lines[0];
string s2 = lines[1]; // Now you can access second line
sr.Close();
test.StartInfo.FileName = s;
test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
test.StartInfo.CreateNoWindow = false;
test.Start();
流程测试=新流程();
字符串FileName=“prefs.dat”;
StreamReader sr=新的StreamReader(文件名);
列表行=新列表();
添加(sr.ReadLine());
添加(sr.ReadLine());
字符串s1=行[0];
字符串s2=行[1];//现在你可以进入第二条线路了
高级关闭();
test.StartInfo.FileName=s;
test.StartInfo.WindowStyle=ProcessWindowStyle.Hidden;
test.StartInfo.CreateNoWindow=false;
test.Start();
您也可以同时读取所有行
string[] lines = System.IO.File.ReadAllLines("path");
因为您只将第一行添加到列表中。您需要在文件中循环,直到EOF
not reach,然后继续将行添加到列表中。