Hodaya Shalom
Hodaya Shalom

Reputation: 4417

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?

Upvotes: 1

Views: 1747

Answers (1)

Hodaya Shalom
Hodaya Shalom

Reputation: 4417

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);

Upvotes: 1

Related Questions