Search code examples
c#asp.netwcfwinapi

The wcf service loses the logs


I have an issue with WCF sessions and log files. WCF is hosted in a Windows services and serves requests from a ASP.NET web application. Each user connect has its own session "in memory" and has a sessions id. Each session initialize a new log class and write logs in different folder for each user. It happens that after some time the file keep growth and date time updated but the rows are not present in the file. I suspect that the buffering of file system or framework doesn't write all rows so I changed to CreateFile Win32 API with NO_BUFFERING options.

SafeFileHandle hcFile = Win32API.CreateFile(@"C:\Temp\File.log", System.IO.FileAccess.Write,
                System.IO.FileShare.Read, IntPtr.Zero,
                System.IO.FileMode.Append,
                (System.IO.FileAttributes)Win32API.FILE_FLAG_NO_BUFFERING, IntPtr.Zero);

        if (!hcFile.IsInvalid) {
            FileStream fs = new FileStream(hcFile, FileAccess.ReadWrite);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("Log row log row log row");
            sw.WriteLine("Log row log row log row");
            sw.WriteLine("Log row log row log row");
        } 

But the handle is always NOT VALID? Do you have any idea?

Thanks


Solution

  • why are you using the win32? You can use the File object just as easily.

    var logFile = System.IO.File.Open(filePath, System.IO.FileMode.Append);
    

    or since you have all your text lines just put then in an array and write all at once.

    System.IO.File.WriteAllLines(filePath,new string[] { "Line 1", "Line 2" , "Line 3"});
    

    One note... if you are writing this via WCF web service, keep in mind that the account the web service is running under will need write permissions to the directory.