Search code examples
c#python-3.xpython-imaging-libraryread-write

Is there a possibility to only write in an image from c# client and read from python server in the same time?


I am currently reading from file like this in python

python server side:

from PIL import Image

img1 = Image.open(
        'p1.png')

img1 = img1.resize((224,224))
img1 = img1.convert('RGB')

C# client side:

    System.IO.File.WriteAllBytes("incomplete.png", bytes);
    if (File.Exists(@"p.png")) 
    {
        File.Delete(@"p.png");
    }
    File.Move(@"incomplete.png", @"p.png");

The issue is that i need to write and to read from that png almost in the same time and it throws from time to time errors that c# client can not access the file IOException: Sharing violation on path


Solution

  • Having multiple programs reading and writing files at the same time is a recipe for disaster. I would encourage you to take a step back and re-consider your design...

    In the mean time, the issues are probably caused by the C# program writing in the file while Python is reading it. One way to avoid these issues is to ensure that the view of the file is always consistent. So, in your C# program, write the file with the name incomplete.png and then, in the next line, rename that file as p.png. As the rename is an atomic operation, the Python file can only "see" either the new file or the old file but not a mixture of the two.