System.IO.IOException was unhandled

I am facing a strange problem.

I have just 2 lines of code -

File.Create (@"C:\test.test");
File.Delete (@"C:\test.test");

When I execute I get the following error and am not able to tackle this problem.
Any help will be appreciated-

System.IO.IOException was unhandled
Message="The process cannot access the file 'C:\\test.test1' because it is being used by another process."
Source="mscorlib"
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

at System.IO.FileInfo.Delete()

at ConsoleApplication4.Program.Main(String[] args) in C:\Documents and Settings\i032271\My Documents\Visual Studio Projects\ConsoleApplication4\Program.cs:line 31

at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)

at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

at System.Threading.ThreadHelper.ThreadStart()

[1825 byte] By [Roopa] at [2007-12-16]
# 1
Hi Roopa,

The create method returns FileStream object and you need to release it.
See code snippet below:


FileStream objFileStream = File.Create(@"C:\test.test");
objFileStream.Close();
File.Delete (@"C:\test.test");

Regards,
Vikram

Vikram at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 2
File.Create returns a filestream which has not been closed when you are trying to delete the file.

You should do:


FileStream file = null;
try {
file=File.Create(...);
}
finally {
if(file!=null)
file.Close();
}
//then you can safely do
File.Delete(...);

darkmark327 at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 3
Roopa

You must first close the file, before deleting it.

Regards,

Marconi

MarconiASJunior at 2007-9-9 > top of Msdn Tech,.NET Development,.NET Base Class Library...

.NET Development

Site Classified