获取一个.txt路径并在其中写入/读取

本文关键字:在其中 读取 路径 txt 一个 获取 | 更新日期: 2023-09-27 18:28:03

我制作了一个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);
            }

获取一个.txt路径并在其中写入/读取

在调用openFD.ShowDialog()之前,您应该在已经有路径的情况下打开流。属性FileName不包含文件路径。

除此之外,我认为在这种情况下创建FileStream是多余的,您可以将path作为参数传递给StreamWriter构造函数,FileStream将在StreamWriter构造函数中创建。

此外,您应该始终使用块或手动调用Dispose()方法将一次性对象(如StreamWriter)放入其中。

所以我的这个函数的变体是这样的:

    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。此函数从路径中提取文件名,例如,对于值C:'My Folder'test.txt,它将返回test.txt。如果文件不在应用程序文件夹中,FileStream将无法仅基于名称而不基于完整路径来查找文件。

显示打开文件对话框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);
            }
     }

将代码放在新的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);
            }
        }
    }