简体   繁体   中英

Access to the path is denied when save with filedialog

I have two forms of saving to a file:

One. I keep the path in the code.

Two. I get the path from the user.

When I save the path in the code, save successful. When I get from the user (the same path that I kept in the code) this fall with the following error:

Access to the path is denied

Here my save function (both ways come to the same function):

public void SaveFile(string path)
{
    try
    {
        XmlSerializer serializer = new XmlSerializer(typeof(List<MyClass>));
        TextWriter textWriter = new StreamWriter(path);
        serializer.Serialize(textWriter, MyList);
        textWriter.Close();
    }
    catch (Exception e)
    {
    }
}

From the user I send to this function as follows:

public void UserSave()
{
    //Open dialog in the path that i have in the code:
    fileDialog.InitialDirectory = MyPath;
    if (fileDialog.ShowDialog() == DialogResult.OK)
    {
        SaveFile(Path.GetDirectoryName(fileDialog.FileName));
    }
}

What could be the problem?

I found the error in the following line:

SaveFile(Path.GetDirectoryName(fileDialog.FileName));

It basically saves it as a folder instead of as a file , so it fell.

I changed it to this:

SaveFile(fileDialog.FileName);

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