简体   繁体   English

使用文件对话框保存时,拒绝访问路径

[英]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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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