我正在制作一个WinForm,以便使用“查找文件”按钮从用户获取.txt路径,将其打印在textBox中,然后能够读取/写入该.txt文件。我找不到一种可能的方法来使这个想法成为可能,我总是在代码中得到错误。窗口:http://prntscr.com/9i46ch。我尝试过的最新代码:
OpenFileDialog openFD = new OpenFileDialog();
openFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
string path = Path.GetFileName(openFD.FileName);
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter str = new StreamWriter(fs);
if (openFD.ShowDialog() == DialogResult.OK)
{
try {
textpathTB.Text = path;
str.Write("Hello!");
}
catch (Exception e)
{
MessageBox.Show("The path was not correct! Original error:" + e.Message);
}
答案 0 :(得分:2)
在调用openFD.ShowDialog()
属性FileName
不包含文件路径之前,您应该在已有路径时打开流。
除此之外,我认为在这种情况下创建冗余FileStream
,您可以将路径作为参数传递给StreamWriter
构造函数,FileStream
将在StreamWriter
构造函数中创建
此外,您应始终将一次性物品(例如StreamWriter
)放入使用块内或手动调用Dispose()
方法。
所以这个函数的变体将是这样的:
OpenFileDialog openFD = new OpenFileDialog();
openFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFD.ShowDialog() == DialogResult.OK)
{
try
{
string path = Path.GetFileName(openFD.FileName);
textpathTB.Text = path;
using(var str = new StreamWriter(openFD.FileName))
{
str.Write("Hello!");
}
}
catch (Exception e)
{
MessageBox.Show("The path was not correct! Original error:" + e.Message);
}
}
您的解决方案中的另一个小错误是在将值传递给流之前调用函数Path.GetFileName
。此函数从路径中提取文件名,例如,它将为值test.txt
返回C:\My Folder\test.txt
。如果文件不在应用程序文件夹中,FileStream
将无法仅在没有完整路径的名称上找到文件。
答案 1 :(得分:1)
显示打开文件对话框ShowDialog ()
OpenFileDialog openFD = new OpenFileDialog();
openFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFD.ShowDialog() == DialogResult.OK)
{
try
{
string path = Path.GetFileName(openFD.FileName);
textpathTB.Text = path;
using(var str = new StreamWriter(openFD.FileName))
{
str.Write("Hello!");
}
}
catch (Exception e)
{
MessageBox.Show("The path was not correct! Original error:" + e.Message);
}
}
答案 2 :(得分:1)
将您的代码放在一个新的Winforms应用程序中,并引发此错误,创建文件流对象:
"空路径名称不合法。"
在获取文件路径之前,您正在创建文件流对象 如果您将代码结构化为完成目标所采取的步骤,它将会有所帮助。
private void CreateFileButton_Click(object sender, EventArgs e)
{
// Open a dialog to get the filepath
// If the user clicked ok
// Try to write out to the file
// Handle exceptions
}
使用构造将您的流对象放入其中也是有益的,这样他们就不会长时间保留文件。
private void CreateFileButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFD = new OpenFileDialog();
openFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFD.ShowDialog() == DialogResult.OK)
{
try
{
string path = Path.GetFileName(openFD.FileName);
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
using (StreamWriter str = new StreamWriter(fs))
{
textpathTB.Text = path;
str.Write("Hello!");
}
}
}
catch (Exception ex)
{
MessageBox.Show("The path was not correct! Original error:" + ex.Message);
}
}
}