asp.net the file read and write operation (read and write Lock) _ Practical skills

Source: Internet
Author: User
Tags readfile
Most of the questions are as follows:

1: Write some content to a file, in another process/thread/subsequent operation to read the contents of the file when the report exception, prompt System.IO.IOException: The file "XXX" is being used by another process, so the process cannot access this file.

2: After some operation on a file (read/write), then want to append still reported System.IO.IOException: File "XXX" is being used by another process, so the process cannot access this file. The second problem is similar to 1.

3: After a few operations on a file, want to delete the file, still reported System.IO.IOException: The file "XXX" is being used by another process, so the process cannot access this file.

Seeing this, experienced students should say that resources have not been released, but there are the following possibilities. We have very frequent operations on the file, so we write a specific operation class/component to maintain the operation between files, know the specific time to end, common such as log, as the program starts to write log, until the program is closed. But there is also a need to provide a special operation (read/write/delete) to manipulate the file, for example, we need to provide a log viewer to view the current log or all the logs, at which point, there will inevitably be the above problems.

Copy Code code as follows:

static void WriteFile (FileMode FileMode, FileAccess fileaccess, FileShare fileshare)
{
Console.WriteLine ("Please input your content.");
var content = Console.ReadLine ();
FileStream fs = new FileStream (FILEPATH, FileMode, FileAccess, FileShare);
var buffer = Encoding.Default.GetBytes (content);
Fs. Write (buffer, 0, buffer.) Length);
Fs. Flush ();
}

First, I declare a write-file method and call it, which writes what I entered into the specified file.
Copy Code code as follows:

WriteFile (FileMode.Create, FileAccess.Write, FileShare.Read);
Console.readkey ();

However, after the write file operation ended, I did not release the resources of the file stream. As a result, a lock is created for the file at this time. I tried to delete it in Windows.

Obviously I can't erase this file, and next, I try to read it.

Copy Code code as follows:

static void ReadFile (FileAccess fileaccess, FileShare fileshare)
{
FileStream fs = new FileStream (FILEPATH, FileMode.Open, FileAccess, FileShare);
var buffer = new Byte[fs. Length];
Fs. Position = 0;
Fs. Read (buffer, 0, buffer.) Length);
Console.WriteLine (Encoding.Default.GetString (buffer));
}

I implemented a read file method and called it.
Copy Code code as follows:

WriteFile (FileMode.Create, FileAccess.Write, FileShare.Read);
ReadFile (FileAccess.Read, FileShare.Read);

Everything is simple, access mode is read-only, so it should not conflict with the above write lock!

However, the results are not what we expected, and why are we prompted for no access? Recall that, in the front, I used Windows Notepad opened this file, and no hint that the file is locked, I do have access, then why the program can not access it? Perhaps we should focus on the three enumerations of Filemode,fileaccess,fileshare, or they might be the ghosts.
FileMode
The explanation on MSDN is to specify how the operating system opens the file, and I think this should not be explained, and we usually use it a lot more. The MSDN table also illustrates the value of each enumeration, and I'm not explaining it.

FileAccess
Defines constants for file read, write, or read/write access.

This enumeration is also used more, the description is also very easy to understand, I also inconvenient to explain. ^_^!

FileShare
Believe that this enumeration type we will be more unfamiliar, and even have not seen the students see (ashamed of IS, I did not know how long it is, unfamiliar to the unfamiliar, but its force is not underestimated, but. NET helps us encapsulate it so much that we once thought it was not an important role. All right, go to the theme!

Contains constants that control the type of access that other FileStream objects can have on the same file. What do you mean by that remark? To tell the truth, I now see a sentence or feel very tangled, I believe many students see is also confused, it does not matter, we first skip!


Look at the description of its members, and FileAccess is very similar, then we try to uncover its temporary mystery of the veil!
FileShare.Read
Literally, we can understand that after opening a file first (the resource is not released), we can read the file in a read-only way without throwing an exception that the file cannot access. Using the method just implemented, you can easily complete this experiment again:

Copy Code code as follows:

WriteFile (FileMode.Create, FileAccess.Write, FileShare.Read);
ReadFile (FileAccess.Read, FileShare.Read);

What the hell is going on here? Is it all set to read? You may only be able to set a read-only share when you are reading a file. Let's try again:

Copy Code code as follows:

ReadFile (FileAccess.Read, FileShare.Read);
ReadFile (FileAccess.Read, FileShare.Read);

This time it is really possible to read the first time without releasing the resources, so let's try again. Can write a file after a read-only share is set:

Copy Code code as follows:

ReadFile (FileAccess.Read, FileShare.Read);
WriteFile (FileMode.Create, FileAccess.Write, FileShare.Read);

First read out the contents of the file correctly, but when I try to write some content, I have an error. Then, based on the above experiments, you can learn that this read-only sharing is only valid in the continuous reading of the file!
Fileshare.write
In combination with Read's experience, the literal meaning should be understood to be that only when writing a file, you set the sharing mode to write, and then you can continue writing to the file, or you will throw an exception. Here is more fun, set write, the Universal window Notepad can not open the file.

Fileshare.readwrite
With the above experience, literally, it can be thought that this readwrite must be a combination of read and write features. What's the use of it anyway? The above we know, in the read file set reading share can continue to read and can not write, write a file when set write share can continue to write but not read, but when we set the write share and want to read the file how to do? Can I only release the resource and reload it first? No, ReadWrite was born for this.

Copy Code code as follows:

WriteFile (FileMode.Create, FileAccess.Write, FileShare.Read);
ReadFile (FileAccess.Read, fileshare.readwrite);

However, when writing files here is not allowed to set the share to write, otherwise read the file with ReadWrite is invalid (reported exception), but are set to ReadWrite can. This will certainly solve many of the day-to-day development of the trouble.
Fileshare.none/fileshare.delete
With the above experience, it is easy to believe that both of you understand, none is not allowed to follow any action, and delete is allowed you to delete later.

The contents of the black box
For file operations, we usually use more of the following types of possibilities:

Copy Code code as follows:

File.appendalltext ("...");
File.appendalllines (...);
File.appendtext (...);
FileStream fs = new FileStream (path, FileAccess.Write);
Fs. Write (...);

In fact, they also initialize the Filemode/fileaccess/fileshare internally, for example, the static method of file will eventually generate a stream instance, in which the private method is invoked

End
Now, we understand that/fileshare is actually the "access" to control the file stream, of course, this is just the entry of the file operation, their own notes, but also hope to bring help to everyone, senior article in the garden has been a lot of predecessors wrote the document read and write lock articles, interested students can have a search, Go to observe!!
Author: Air Yat Yun

Related Article

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.