C# 读取 INI 文件:解决访问拒绝问题
在 C# 中读取 INI 文件时,可能会遇到 "对路径 '\192.168.11.248\软件\勿删\高功率效率测试值\测试值.ini' 的访问被拒绝" 的错误。
这可能是因为你的程序没有足够的权限来访问该文件。你可以尝试以下几种解决方案:
-
以管理员身份运行程序
- 右键点击你的程序的执行文件,选择 "以管理员身份运行"。
-
将文件复制到一个你的程序有权限访问的位置
- 例如,你可以将文件复制到你的程序目录下。
-
使用 UNC 路径
- UNC 路径是指网络文件路径,例如 "\localhost\share\file.ini"。使用 UNC 路径可以绕过访问权限问题,因为你只需要提供访问网络资源的凭证。
以下是一个读取 INI 文件的 C# 代码示例:
public string GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpFileName)
{
string path = Path.GetFullPath(lpFileName);
if (!File.Exists(path))
{
return lpDefault;
}
string value = lpDefault;
try
{
using (StreamReader sr = new StreamReader(path, Encoding.Default))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith(';') || line.StartsWith('#'))
{
continue;
}
if (line.StartsWith('[') && line.EndsWith(']'))
{
string section = line.Substring(1, line.Length - 2);
if (section.Equals(lpAppName, StringComparison.OrdinalIgnoreCase))
{
while ((line = sr.ReadLine()) != null)
{
if (line.StartsWith(';') || line.StartsWith('#'))
{
continue;
}
int index = line.IndexOf('=');
if (index >= 0)
{
string key = line.Substring(0, index).Trim();
string val = line.Substring(index + 1).Trim();
if (key.Equals(lpKeyName, StringComparison.OrdinalIgnoreCase))
{
value = val;
break;
}
}
}
break;
}
}
}
}
}
catch (Exception ex)
{
value = lpDefault;
}
return value;
}
注意:
- 使用 UNC 路径时,你需要确保你的程序有访问该网络资源的权限。
- 如果你的程序需要频繁地访问 INI 文件,建议使用其他更安全可靠的方法,例如数据库或 XML 文件。
希望这篇文章能帮助你解决 INI 文件访问拒绝的问题。
原文地址: https://www.cveoy.top/t/topic/mkTU 著作权归作者所有。请勿转载和采集!