我正在尝试弄清楚如何用StreamReader读多行。我有一个文本文件,里面有一个命令列表,我需要从中读取。我的代码可以工作,但是它只会读取第一行。这导致我不得不将所有命令移动到一行,中间有一个空格。这不是一种非常整洁的方式,因为我需要在命令旁边留下注释。示例: CONNECT:“连接到给定的IP。”
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
if (e.KeyCode == Keys.Enter)
{
// Read the file and display it line by line.
StreamReader file = new StreamReader("C:\\Users\\Home\\Desktop\\commands.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(ConsoleEnter.Text))
{
COMBOX.Items.Add(ConsoleEnter.Text);
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
else
{
COMBOX.Items.Add("Invalid Command");
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
}
}发布于 2013-05-16 12:55:03
这是我在我的一个应用程序中使用的,它工作得很好,希望它能帮助你......
if (TxtPath.Text != string.Empty)
{
StreamReader srr = new StreamReader(TxtPath.Text);
try
{
ss = srr.ReadToEnd().Split('\n');
MessageBox.Show("File Successfully Loded in Memory \n" + TxtPath.Text, "System Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
throw new Exception("File are not readable or write protacted");
}
LblLineCount.Text = ss.Count().ToString();
}
else
{
MessageBox.Show("Please Browse any Log File 1st", "System Manager", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}你也可以修剪.Split('\n'),在一行中获取所有数据,我现在不能尝试,但如果选中它,将使你摆脱卡住.
发布于 2013-05-16 12:42:23
U应该在循环之后清空变量,而不是在循环内部
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
if (e.KeyCode == Keys.Enter)
{
// Read the file and display it line by line.
StreamReader file = new StreamReader("C:\\Users\\Home\\Desktop\\commands.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(ConsoleEnter.Text))
{
COMBOX.Items.Add(ConsoleEnter.Text);
}
else
{
COMBOX.Items.Add("Invalid Command");
}
}
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}发布于 2013-05-16 12:45:08
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
string path = @"C:\\Users\\Home\\Desktop\\commands.txt";
WebClient client = new WebClient();
System.IO.Stream stream = client.OpenRead(path);
System.IO.StreamReader str = new StreamReader(stream);
string Text=str.ReadToEnd();
string[] words = Text.Split(':');
if (e.KeyCode == Keys.Enter)
{
for(int i=1;i<words.Length;i++)
{
if (string.compare(words[i],textBox1.text)==0)
{
COMBOX.Items.Add(ConsoleEnter.Text);
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
else
{
COMBOX.Items.Add("Invalid Command");
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
}
}试试这个..。通过System.Net使用命名空间;
https://stackoverflow.com/questions/16579021
复制相似问题