A
A
anonymous2017-07-15 14:54:32
.NET
anonymous, 2017-07-15 14:54:32

Why might others overwrite the file?

I put FileShare.Read or .None - but for some reason it does not work
Another user (the second open application can still open and resave)
And I need only one user to be able to resave, while others cannot, until the end of work with the file

using(FileStream fs = new FileStream(openFileDlg.FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                        {
                            try
                            {
                                int size = (int)fs.Length;
                                byte[] buffer = new byte[size];
                                int count = 0;
                                int sum = 0;
                                while ((count = fs.Read(buffer, sum, size - sum)) > 0)
                                {
                                    sum += count;
                                }
                                textBox.Text = Encoding.UTF8.GetString(buffer);
                            }
                            finally
                            {
                                if (fs != null)
                                    fs.Close();
                            }
                        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
eRKa, 2017-07-21
@anonymouss

The question is not entirely clear. If the user's access rights to the file are needed, they must be checked before reading the file.
In theory, while the stream is open, then access to the file will be blocked, when you try to get another access, an exception will pop up. You can see if after while put a breakpoint or thread.sleep and try to read the file from the second application.
And if the creation of the thread is hidden in using, then there is no point in hiding the code in try/finally and manually calling close(). Using is just designed not to worry about this, it itself unfolds into a try / finally, in which the stream will close.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question