您好我想使用对话框表单选择文本文件,而不是必须使用给定的路径。我该怎么做?
我想用opendialog替换opentext?我已经尝试但是我得到了流的错误我想使用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();
}
答案 0 :(得分:4)
你想要这样的东西吗?
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
using (var reader = File.OpenText(dlg.FileName))
{
...
}
}
答案 1 :(得分:2)
private void button2_Click(object sender, EventArgs e)
{
string fileToOpen = "";
OpenFileDialog dialog = new OpenFileDialog();
dialog.Title = "Browse for file...";
dialog.RestoreDirectory = true;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
fileToOpen = dialog.FileName;
}
using (StreamReader reader = File.OpenText(fileToOpen))
{
label3.Text = "Ready to Insert";
textBox7.Text = reader.ReadLine();
textBox8.Text = reader.ReadLine();
textBox9.Text = reader.ReadLine();
textBox10.Text = reader.ReadLine();
}
}
答案 2 :(得分:2)
我想用 opendialog 替换opentext?我试过但是我得到了 流错误我想使用streamreader ....
解决方案1:您可以将Stream
返回的openFileDialog.OpenFile()
分配给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
属性
Path
参数分配给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();
}
}
解决方案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分配到从textBox3
到textBox23
的20个Textbox控件,则需要更改上述代码中的参数,如下所示:
preText="textBox";
startCount = 3;
endCount = 23;