Unable to read bytes from the file via ReadAllBytes . File is busy by another process. How can I somehow get the bytes from this file? And this process is preferably not to kill.
- If the process is not yours, and the file is opened in the non-shared mode, then neither - Vasek
|
1 answer
It is with the help of the ReadAllBytes method ReadAllBytes I am not sure what can be done. But a slightly different way you can do. For this we use FileStream and StreamReader . For FileStream key attribute is FileShare.ReadWrite . Sample working code:
byte[] bytes; string text; using (FileStream stream = File.Open("C:\\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (StreamReader reader = new StreamReader(stream)) { // прочитаем весь текст из файла text = reader.ReadToEnd(); } } // конвертируем строку в массив байт bytes = Encoding.ASCII.GetBytes(text); The efficiency of this approach is checked. Opened a text document at the same time in the list of programs (Notepad, Notepad ++, WordPad, Word 2016) and launched the program - read everything without errors.
Useful links:
- Notepad does not lock the file. Lachit - Word, for example. - nick_n_a
- @nick_n_a checked with Notepad ++, WordPad and Word - everything works - Denis Bubnov
- Does not work. System.IO.IOException: "The process cannot access the file" H: \ yyy \ BlueStacks \ Android \ Data.sparsefs \ store "because this file is being used by another process." - Mart
- @Mart is very interesting ... I suspect that the process is blocking everything. Can a plain text editor open this file? Try to open it with a text editor while there is an exception. And yet, did you specify all the attributes correctly? About
FileShare.ReadWritenot forgotten? - Denis Bubnov - A plain text editor also does not open. Indicated everything as you wrote. - Mart
|