0

I keep getting " process cannot access the file '" error . i have researched it enough but cannot find answers. infact this stackoverflow article demonstrates the issue without a solution. another example

How do i read and write to the same file ?

i have a process writing json file using the following logic

private void write2fileJson(string str, string filename, bool append = true)
    {
      //  Print(str);
        using (System.IO.StreamWriter file1 =
                new System.IO.StreamWriter(filename + ".json", append))
        {
            file1.WriteLine(str);
            file1.Flush();

        }
    }

I do have another process reading it.

 using (var s = new FileStream(StrategyFileWithpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var tr = new StreamReader(s))
                {
                    StrategyStateJson = tr.ReadToEnd();
                }
            }

i end up getting process blocked file when i am trying to read it.

System.IO.IOException: The process cannot access the file 'd:\strategyfiles\GBPUSD.json' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at NinjaTrader.NinjaScript.Indicators.ProfitabilityPlots.GetStrategyState() in d:\My Documents\NinjaTrader 8\bin\Custom\Indicators\ProfitabilityPlots.cs:line 150
   at NinjaTrader.NinjaScript.Indicators.ProfitabilityPlots.OnChanged(Object source, FileSystemEventArgs e) in d:\My Documents\NinjaTrader 8\bin\Custom\Indicators\ProfitabilityPlots.cs:line 268
   at System.IO.FileSystemWatcher.OnChanged(FileSystemEventArgs e)
   at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* overlappedPointer)
   at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
junkone
  • 1,427
  • 1
  • 20
  • 45
  • 2
    Simply use `lock` on the same object in both methods. – Poul Bak Jul 06 '23 at 19:54
  • Probably you have to set FileShare.ReadWrite to code that writes to file. – PsiHamster Jul 06 '23 at 21:40
  • If you have two processes, one writing a file and one reading, you will likely get some of this sometime. Read up on the FileShare behavior and on the file locking behavior of FileStream (and File and StreamWriter). You may have to do a careful dance to get it right – Flydog57 Jul 06 '23 at 21:45

0 Answers0