• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 36
  • Last Modified:

Checking if file is open before writing to it.

I want to write to a file using a streamwriter.

using (StreamWriter sw = new StreamWriter(@"D:\Documents\MathsPrograms\Prime2.csv", false))
                {
}

Open in new window


How can I get the program to give an error message if the file is locked eg another program is writing to it, or a user has the file open in Excel?
0
AlHal2
Asked:
AlHal2
  • 2
  • 2
1 Solution
 
Russ SuterCommented:
Enclose it in a try/catch block and catch the exception.
0
 
AlHal2Author Commented:
Is that standard practice?  I thought it would slow down the app or use up memory unnecessarily.
0
 
Russ SuterCommented:
It's true that try/catch blocks are overused and there certainly is a performance cost involved. Where possible, you should write code that does not rely on try/catch blocks. However, in this case you have a couple of things which make it an appropriate approach in this case.

1. What you are trying to check for is, in fact, an exception case.
2. There is no method for detecting whether a file is locked without actually trying to access the file.
3. The StreamWriter class is going to throw the exception regardless of what code you write.
4. You can minimize the impact of what you're trying to do by not creating a generic try/catch block. Instead, only catch the error that you're specifically looking for. Here's a basic example.
		public bool IsFileLocked(string filename)
		{
			try
			{
				using (System.IO.StreamWriter writer = new System.IO.StreamWriter(filename, false))
				{
					
				}
			}
			catch (System.IO.IOException)
			{
				return true;
			}
			return false;
		}

Open in new window

0
 
AlHal2Author Commented:
Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now