2

I'm trying to figure out a way to lock multiple files at the same time. For example, I want to lock test1.txt test2.txt but not lock the rest of the files in the folder.

I currently lock the files by using:

FileStream fileStream = new FileStream("C:\\pathoffile\test1.txt", FileMode.Open,     FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader streamReader = new StreamReader(fileStream);

fileStream.Lock();

//this is where i check if the file is indeed locked or not

streamReader.Close();
fileStream.Close();

This works perfectly fine, however I do not want to do this for every file that I lock. I was wondering if there was a simpler way to lock multiple files at once?

Thanks

  • Duplicate http://stackoverflow.com/questions/1304/how-to-check-for-file-lock-in-c – craig1231 Jan 31 '12 at 20:23
  • how is that a duplicate? – user1181258 Jan 31 '12 at 20:26
  • Probably because you say: `//this is where i check if the file is indeed locked or not` It's not a duplicate of the rest of the question, though. – Cody Gray - on strike Jan 31 '12 at 20:27
  • That is not the question though. I do not need to know how to check locked files. – user1181258 Jan 31 '12 at 20:28
  • What don't you like about this solution? Is it just ugly to you? Too much code? Does it perform slowly? If it's just too much code or inconvenient to type you can throw it all into a method so that you don't need to look at it every time you use it. – Servy Jan 31 '12 at 20:31
  • What I do not like about it, is the fact that I would have to create a filestream, streamreader for each file that I want to lock. I was thinking maybe there is a way, which I do not know about, that might make this easier, quicker, etc. For example, if I want to lock 100txt files. – user1181258 Jan 31 '12 at 20:34
  • Why on God's green earth would you need to lock 100 files at the same time? – Cody Gray - on strike Jan 31 '12 at 20:49

1 Answers1

0

Unfortunately, this is not possible. I can't think of any workaround.

Why do you want to lock files? Maybe we can find a different solution altogether.

usr
  • 168,620
  • 35
  • 240
  • 369
  • I am testing locked files, and I need to lock a large number of files. Do not want to lock each file using the method in the original post. – user1181258 Jan 31 '12 at 20:29
  • Why do you want to lock them? What files are they? – usr Jan 31 '12 at 20:32
  • If there is an absolute requirement to lock those files without opening them, my answer stands. There is no way to do it. No API for that available. – usr Jan 31 '12 at 20:38
  • I need to absolutely lock these files. I need them so no program can use them. – user1181258 Jan 31 '12 at 20:40
  • Are you going to open the files to write to them? If so then can't you just use [FileShare.None](http://msdn.microsoft.com/en-us/library/aa272130%28v=vs.60%29.aspx)? – Raj Ranjhan Jan 31 '12 at 21:25