C # When reading and writing a file, the file is being used by another process, so the process cannot access the file

Source: Internet
Author: User

C # When reading and writing a file, the file is being used by another process. Therefore, the process cannot access the file and encounters an I/O failure.

The file "D: \ log.txt" is being used by another process, so the process cannot access the file.

Log.txt is a log file and may be written to it by another program from time to time.

I/O streams need to be used to read log files and display them in log query.

1. filestream FS = file. openread (URL );
Streamreader sr = new streamreader (system. Io. Stream) FS, system. Text. encoding. Default );

Error message: the file "D: \ log \ cargoabc \ logfilecargoabc.txt" is being used by another process. Therefore, this process cannot access the file.

2. streamreader sr = file. opentext (URL );

Error prompt: the error message "D: \ log \ cargoabc \ logfilecargoabc.txt" is being used by another process. Therefore, this process cannot access the file.

3. filestream FS = new filestream (URL, filemode. Open, fileaccess. Read, fileshare. readwrite );
Streamreader sr = new streamreader (FS, system. Text. encoding. Default );

Read correctly.

Summary:

In this case, you do not only need to open the TXT file in read-only mode, but also need to share the lock. You must also select the flieshare mode as readwrite. Because there are other programs to write to it at any time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.