在app文件夹中创建文件时出现System.UnauthorizedAccessException

时间:2011-10-16 09:01:48

标签: .net winforms

我有Winforms应用程序,必须在使用期间创建对某些配置文件的写入。一旦我使用调试模式,这个文件可以创建并写入它,但是一旦我创建安装项目并实际安装应用程序,我无法访问以下异常。

配置文件与程序(在程序文件中)位于同一目录

我用来读/写的代码是。

public static string[] GetDefaultConfigFile(string path)
{
    string[] res = {};
    if (File.Exists(GetInternalFileName(path)))
    {
        using (StreamReader tr = new StreamReader(GetInternalFileName(path)))
        {
            res = tr.ReadToEnd().Split(';');
        }
    }
    return res;
}

public static void SaveDefaultConfigFile(string fileName, string path)
{
    using (var tw = new StreamWriter(GetInternalFileName(path)))
    {
        tw.Write(fileName);
        tw.Close();
    }
}

private static string GetInternalFileName(string path)
{
    return path + "\\setup.config";
}

1 个答案:

答案 0 :(得分:1)

也许用于运行此代码的帐户没有足够的权限来写入指定的文件夹(Program Files)。如果您在Windows 7或Vista下运行,则标准用户无权写入此文件夹。在这种情况下,您可以使用用户specific folder c:\users\username来存储配置设置。

我也会简化:

public static string[] GetDefaultConfigFile(string path)
{
    return File.ReadAllText(path).Split(';');
}

public static void SaveDefaultConfigFile(string fileName, string path)
{
    File.WriteAllText(path, fileName);
}

private static string GetInternalFileName(string path)
{
    return Path.Combine(path, "setup.config");
}