Doa
Doa

Reputation:

C#: Check if a file is not locked and writable

I want to check if a list of files is in use or not writable before I start replacing files. Sure I know that the time from the file-check and the file-copy there is a chance that one or more files is gonna to be locked by someone else but i handle those exceptions. I want to run this test before file copy because the complete list of files have a better chance to succeed than if a file in the middle of the operation fails to be replaced.

Have any of you an example or a hint in the right direction

Upvotes: 13

Views: 19640

Answers (4)

user142650
user142650

Reputation:

There is no guarantee that the list you get, at any point of time, is going to stay the same the next second as somebody else might take control of the file by the time you come back to them.

I see one way though - "LOCK" the files that you want to replace by getting their corresponding FileStream objects. This way you are sure that you have locked all "available" files by opening them and then you can replace them the way you want.

public void TestGivenFiles(List<string> listFiles)
{
  List<FileStream> replaceAbleFileStreams = GetFileStreams(listFiles);


    Console.WriteLine("files Received = " + replaceAbleFileStreams.Count);
    foreach (FileStream fileStream in replaceAbleFileStreams)
    {
        // Replace the files the way you want to.
        fileStream.Close();
    }
}

public List<FileStream> GetFileStreams(List<string> listFilesToReplace)
{
    List<FileStream> replaceableFiles = new List<FileStream>();
    foreach (string sFileLocation in listFilesToReplace)
    {
        FileAttributes fileAttributes = File.GetAttributes(sFileLocation);
        if ((fileAttributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
        { // Make sure that the file is NOT read-only
            try
            {
                FileStream currentWriteableFile = File.OpenWrite(sFileLocation);
                replaceableFiles.Add(currentWriteableFile);
            }
            catch 
            {
                Console.WriteLine("Could not get Stream for '" + sFileLocation+ "'. Possibly in use");
            }
        }
    }
    return replaceableFiles;
}

That said, you are better off trying to replace them one by one and and ignore the ones that you can't.

Upvotes: 10

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391634

You must open each file for writing in order to test this.

Upvotes: 0

maxwellb
maxwellb

Reputation: 13964

Read one byte, write same byte?

Upvotes: -5

Related Questions