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?
AlHal2Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AlHal2Author Commented:
Thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.