Avatar of AlHal2
AlHal2
Flag for United Kingdom of Great Britain and Northern Ireland asked on

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?
C#

Avatar of undefined
Last Comment
AlHal2

8/22/2022 - Mon
Russ Suter

Enclose it in a try/catch block and catch the exception.
AlHal2

ASKER
Is that standard practice?  I thought it would slow down the app or use up memory unnecessarily.
ASKER CERTIFIED SOLUTION
Russ Suter

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
AlHal2

ASKER
Thanks.
Your help has saved me hundreds of hours of internet surfing.
fblack61