简体   繁体   中英

Writing a File to the Specified Folder

This question is in conjunction with my other: Write a text file to a sub-folder .

This time, I have a program that has a text folder to open a file, then extract data from that file. Then I can save it by saying where to save it.

private void btnExtract1_Click(object sender, EventArgs e)
{
    btnExtract1.Enabled = false;
    string path = txtSave1.Text;

    string file1;
    using (StreamReader reader = new StreamReader(File.OpenRead(txtFile1.Text)))
    using (StreamWriter writer = new StreamWriter(path))
    {
        while ((file1 = reader.ReadLine()) != null)
        {
            file1 = file1.Replace("\"", string.Empty);
            file1 = file1.Substring(0, 8);

            line_number1 += 1;

            if (line_number1 >= 1)
            {
                writer.WriteLine(file1);
            }
        }
    }
    btnExtract1.Enabled = true;
}

private void btnSave1_Click(object sender, EventArgs e)
{
    DialogResult result = savefile1.ShowDialog();
    txtSave1.Text = savefile1.FileName;
}

No it is not saving in that folder. In fact, it breaks at:

using (StreamWriter writer = new StreamWriter(path))

With this error:

A first chance exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll

What could possibly be wrong?

Did you check how your path looks like? Maybe you're not escaping the \\ properly or you have some invalid characters inside your path.

I made a rookie mistake, where I forgot to say what file it is to save as.

using (StreamWriter writer = new StreamWriter(path))

Where path is equal to whatever the user wants it as - in my case it was set to C:\\temp\\ . I haven't set the SaveFileDialog to save as any default name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM