我继承了一组 .NET 项目的开发职责,其中包括 Windows 服务、一个 ASP.NET 网站和通过任务管理器启动的标准可执行文件。
所有这些组件都连接到 MySQL 数据库。目前,加密的连接字符串位于单独的 app.config/web.config 文件中。我认为必须在多个地方更新连接字符串是一种痛苦,所以我想将连接字符串放在一个文本文件中,所有单独的组件都可以访问该文件。
在我全力推进之前,我想问一下我是否可能会引入一个错误,因为可能有多个进程试图同时访问这个文本文件。我已经编写了一个读取文本文件的通用方法,并且我小心地确保以“读取”模式打开文件:
public string AESDecryptFromFile(string path, string password, string IV)
{
if (!File.Exists(path))
throw new Exception("File not found: " + path);
string cryptogram;
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fs))
{
cryptogram = sr.ReadToEnd().Trim(new char[] { '\r', '\n', ' ' });
}
}
return AESDecrypt(cryptogram, password, IV);
}
如果我以这种方式实现它,我没有任何理由相信进程会锁定文件,但我想我会问。
提前致谢!
默认情况下,使用(string path, FileMode mode, FileAccess access)
of的构造函数也FileStream
将获得以下配置:
因为您不希望该进程锁定文件,所以这对您来说是完美的,因为您需要只读(请参阅https://msdn.microsoft.com/en-us/library/system.io.fileshare( v=vs.110).aspx )
但是,如果您想显式,您可以使用以下构造函数:
FileStream s = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.Read);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句