简体   繁体   中英

Reading A File While It is writed by another process

I have an application uses C://root folder. This folder contains images. These images are readed by Pictureboxes.

  1. Images are coming from a linux machine by FTP. A linux machine uses ftp to open C://root which is in the windows. Save the IMAGE_1.jpg.
  2. IMAGE_1.jpg is readed by C# windows form application to show in the picturebox.

Images are coming every 10 second from linux machine. Windows shows these images in a thread.

Sometimes, linux or windows send exception. Because while one of them trying to read image to show(windows), the other is trying to save the image(linux)

Therefore, I have to understand that, if Image_1.jpg is used by linux machine, do not try to show the image in win form.

But how?

In your Win Forms app, open the file for read, and share the file with other processes so they can keep reading/writing to the file.

Use the File.Open Method (String, FileMode, FileAccess, FileShare) to do this.

If you just use File.Open Method (String, FileMode) or File.Open Method (String, FileMode, FileAccess) then the file will be unshared.

By sharing, you should be keeping the ftp side of things happy.

If you get an exception while trying to open the file in Windows - that's fine. Just catch the exception and try again soon.

When you successfully open the file, check if the last two bytes are FF D9. In this case your JPG has finished being uploaded.

Here's some pseudo code.


    success = false
    using (FileStream fs = File.Open(path,  // eg your Image1.jpg
                                     FileMode.Open,
                                     FileAccess.Read, // we just need to read
                                     FileShare.ReadWrite)) // important to share!
    {
       // if last two bytes are FF D9 then
       //    success = true... can display image now
    }
    if (!success)
    {
       // file is being uploaded, or some other problem occurred
       // try again later
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM