C# 将opentext更改为opendialog
您好,我想使用对话框形式选择文本文件,而不必使用给定的路径。我该怎么做 我想用opendialog替换opentext?我已经尝试过了,但是我在使用streamreader时遇到了错误C# 将opentext更改为opendialog,c#,C#,您好,我想使用对话框形式选择文本文件,而不必使用给定的路径。我该怎么做 我想用opendialog替换opentext?我已经尝试过了,但是我在使用streamreader时遇到了错误 private void button2_Click(object sender, EventArgs e) { using (StreamReader reader = File.OpenText("c:\\myparts.txt")) {
private void button2_Click(object sender, EventArgs e)
{
using (StreamReader reader = File.OpenText("c:\\myparts.txt"))
{
label3.Text = "Ready to Insert";
textBox7.Text = reader.ReadLine();
textBox8.Text = reader.ReadLine();
textBox9.Text = reader.ReadLine();
textBox10.Text = reader.ReadLine();
}
你想要这样的吗
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
using (var reader = File.OpenText(dlg.FileName))
{
...
}
}
我想将opentext替换为opendialog?我已经试过了,但还是失败了
流错误我想使用streamreader
private void button2_Click(object sender, EventArgs e)
{
using (StreamReader reader = File.OpenText("c:\\myparts.txt"))
{
label3.Text = "Ready to Insert";
textBox7.Text = reader.ReadLine();
textBox8.Text = reader.ReadLine();
textBox9.Text = reader.ReadLine();
textBox10.Text = reader.ReadLine();
}
解决方案1:您可以将openFileDialog.OpenFile()
返回的Stream
分配给StreamReader
试试这个:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using (var reader = new StreamReader(openFileDialog1.OpenFile()))
{
label3.Text = "Ready to Insert";
textBox7.Text = reader.ReadLine();
textBox8.Text = reader.ReadLine();
textBox9.Text = reader.ReadLine();
textBox10.Text = reader.ReadLine();
}
}
解决方案2:您可以直接将openFileDialog().FileName
属性指定为
File.OpenText()方法的路径
参数,如下所示:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using (var reader = new StreamReader(openFileDialog1.OpenText(openFileDialog1.FileName)))
{
label3.Text = "Ready to Insert";
textBox7.Text = reader.ReadLine();
textBox8.Text = reader.ReadLine();
textBox9.Text = reader.ReadLine();
textBox10.Text = reader.ReadLine();
}
}
preText="textBox";
startCount = 3;
endCount = 23;
解决方案3:如果要将文件内容分配给多个文本框
试试这个:
int startCount=7;
int endCount=10;
string preText="textBox";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
String fileName=openFileDialog1.FileName;
foreach(var line in File.ReadLines(fileName))
{
((TextBox) (this.Controls.Find(preText+startCount,true)[0])).Text=line;
if(startCount==endCount)
break;
startCount++;
}
}
注意1:所有TextBoxControl都应以preText
值启动。
注2:在上述解决方案中,您可以根据需要更改startCount
和endCount
例如,如果要将文件contenet分配给20个文本框控件,从textBox3
到textBox23
,则需要按如下方式更改上述代码中的参数:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using (var reader = new StreamReader(openFileDialog1.OpenText(openFileDialog1.FileName)))
{
label3.Text = "Ready to Insert";
textBox7.Text = reader.ReadLine();
textBox8.Text = reader.ReadLine();
textBox9.Text = reader.ReadLine();
textBox10.Text = reader.ReadLine();
}
}
preText="textBox";
startCount = 3;
endCount = 23;
Opendialog返回所选文件的路径,而不是流,您需要将其用作opentext的参数。如果这是您使用的解决方案。请随意“检查”这个作为答案很高兴我能帮忙。