白天在公司发现使用ConfigurationManager写不了app.config文件,按网上说的做的,不懂为什么 不知道有没有其他办法? 还有另外一个问题,c#很不好定位配置文件,或者其他要使用的文件的路径
project/
image/
config/
config.cfg
要如何程序中定位image和config目录?
我在vs中调试时,是从Debug/Bin/目录后退两层,有没有其他方便的方法?
project/
image/
config/
config.cfg
要如何程序中定位image和config目录?
我在vs中调试时,是从Debug/Bin/目录后退两层,有没有其他方便的方法?
2. 用相对路径可以的啊,用Application.StartupPath感觉差不太多.
File.Exists(Application.StartupPath + "\\project.txt")
http://tonghuashuai.jhost.cn/?p=420这种方法的另一个好处是计算机上的不同用户拥有不同的设置。
/// <summary>
/// 取得指定的配置文件对象
/// </summary>
/// <returns></returns>
private static Configuration GetConfig()
{
Configuration cf = ConfigurationManager.OpenExeConfiguration(Application.StartupPath + "\\MainFrm.exe");
if (cf == null)
{
throw new Exception("MainConfigFile-\"MainFrm.exe.config\" Not Found!");
}
return cf;
} /// <summary>
/// 读取配置文件
/// </summary>
/// <param name="strKey"></param>
/// <returns></returns>
public static string ReadMainConfigFile(string strKey)
{
Configuration cf = GetConfig();
string strValue = null;
try
{
strValue = cf.AppSettings.Settings[strKey].Value;
}
catch
{
throw new Exception("MainConfigFile-\"MainFrm.exe.config\" Null Key Read!");
}
if (strValue == null || strValue.Trim().Length == 0)
{
throw new Exception("MainConfigFile-\"MainFrm.exe.config\" Null Value Read!");
}
else
{
return strValue.Trim();
}
}/// <summary>
/// 改写配置文件
/// </summary>
/// <param name="strKey"></param>
/// <param name="strValue"></param>
public static void WriteMainConfigFile(string strKey, string strValue)
{
Configuration cf = GetConfig();
if (strValue == null || strValue.Trim().Length == 0)
{
throw new Exception("MainConfigFile-\"MainFrm.exe.config\" Null Value Write!");
}
else
{
try
{
cf.AppSettings.Settings[strKey].Value = strValue.Trim();
cf.Save();
}
catch
{
throw new Exception("MainConfigFile-\"MainFrm.exe.config\" Null Key Write!");
}
}
}
另外用户的数据文件夹路径可以在程序启动的时候,通过Application.StartupPath属性+自定义路径进行设置和寻找。最好定义成静态公共属性
如果要修改的话还是用XML吧
多谢指点,windows程序默认不是以项目根目录为运行目录