嗨,我想选择文本文件使用对话框形式,而不是必须使用给定的路径。我该怎么做?
我想用Open对话框代替opentext吗?我试过了,但是我在流中遇到了错误,我想使用流阅读器.
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();
}发布于 2014-02-19 20:21:36
我想用open对话框代替opentext吗?我试过了,但是我在流中遇到了错误,我想使用流阅读器.
解决方案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属性作为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: All TextBoxControls应以preText值启动。
备注2:在上面的解决方案中,您可以根据需要更改startCount和endCount。
例如,如果要将文件内容集分配给从textBox3到textBox23的20个Textbox控件,则需要更改上述代码中的参数,如下所示:
preText="textBox";
startCount = 3;
endCount = 23;发布于 2014-02-19 20:17:46
你想要这样的东西吗?
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
using (var reader = File.OpenText(dlg.FileName))
{
...
}
}发布于 2014-02-19 20:20:45
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();
}
}https://stackoverflow.com/questions/21891400
复制相似问题