Search code examples
c#klocwork

klocwork Error: No permission set for resource 'streamWriter' before accessing it


With some help from this article,

https://support.roguewave.com/documentation/klocwork/en/10-x/cs.nps/

I am still getting klocwork error, even after explicitly setting security. Any solution to resolve it.

It's giving error for below line of code,

streamWriter.WriteLine("Hello");

Here is full code,

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");
            }
        }

Solution

  • I know it might be too late to answer. But after come across with multiple try, this is how I escape from getting this CS.NPS klocwork error although code does not seem efficient. Trying with SetAccessControl is also not satisfied klocwork error.

    So, instead of using streamWriter to write, just directly using File.AppendAllText(string path, string content)

    Example:

    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);
    

    But if you happen to write to the same file within a fraction of second (i.e. calling File.AppendAllText(Textwritefile , content) method multiple times) , you might have to add lock in order to avoid getting the error : "The process cannot access the file because it is being used by another process".