klocwork Error: No permission set for resource 'streamWriter' before accessing it
klocwork Error: No permission set for resource 'streamWriter' before accessing it
在这篇文章的帮助下,
https://support.roguewave.com/documentation/klocwork/en/10-x/cs.nps/
即使在明确设置安全性之后,我仍然收到 klocwork 错误。解决它的任何解决方案。
以下代码行出错,
streamWriter.WriteLine("Hello");
这是完整的代码,
using (var stream = new FileStream(@"C:\sample.txt", FileMode.Create))
{
var security = new System.Security.AccessControl.FileSecurity();
security.AddAccessRule(new FileSystemAccessRule(@"domain\user", FileSystemRights.Modify, AccessControlType.Allow));
stream.SetAccessControl(security);
using (var streamWriter = new StreamWriter(stream))
{
streamWriter.WriteLine("Hello");
}
}
我知道现在回答可能为时已晚。
但是在多次尝试之后,这就是我如何避免出现这个 CS.NPS klocwork 错误,尽管代码看起来效率不高。
尝试使用 SetAccessControl 也不满意 klocwork 错误。
所以,不用streamWriter写,直接用File.AppendAllText(string path, string content)
示例:
string Textwritefile = "D:\Working\WriteFile.txt";
string content = "This is testing....";
// Error Code :
using (FileStream fs = new FileStream(Textwritefile , FileMode.Append, FileAccess.Write))
{
fs.SetAccessControl(new FileSecurity(writefilename, AccessControlSections.Access));
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(content); //CS.NPS error comes from this line.
}
}
// Fixed code :
File.AppendAllText(Textwritefile , content);
但是如果你碰巧在几分之一秒内写入同一个文件(即多次调用 File.AppendAllText(Textwritefile , content) 方法),你可能必须添加锁以避免获取错误:"The process cannot access the file because it is being used by another process"。
在这篇文章的帮助下,
https://support.roguewave.com/documentation/klocwork/en/10-x/cs.nps/
即使在明确设置安全性之后,我仍然收到 klocwork 错误。解决它的任何解决方案。
以下代码行出错,
streamWriter.WriteLine("Hello");
这是完整的代码,
using (var stream = new FileStream(@"C:\sample.txt", FileMode.Create))
{
var security = new System.Security.AccessControl.FileSecurity();
security.AddAccessRule(new FileSystemAccessRule(@"domain\user", FileSystemRights.Modify, AccessControlType.Allow));
stream.SetAccessControl(security);
using (var streamWriter = new StreamWriter(stream))
{
streamWriter.WriteLine("Hello");
}
}
我知道现在回答可能为时已晚。 但是在多次尝试之后,这就是我如何避免出现这个 CS.NPS klocwork 错误,尽管代码看起来效率不高。 尝试使用 SetAccessControl 也不满意 klocwork 错误。
所以,不用streamWriter写,直接用File.AppendAllText(string path, string content)
示例:
string Textwritefile = "D:\Working\WriteFile.txt";
string content = "This is testing....";
// Error Code :
using (FileStream fs = new FileStream(Textwritefile , FileMode.Append, FileAccess.Write))
{
fs.SetAccessControl(new FileSecurity(writefilename, AccessControlSections.Access));
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(content); //CS.NPS error comes from this line.
}
}
// Fixed code :
File.AppendAllText(Textwritefile , content);
但是如果你碰巧在几分之一秒内写入同一个文件(即多次调用 File.AppendAllText(Textwritefile , content) 方法),你可能必须添加锁以避免获取错误:"The process cannot access the file because it is being used by another process"。