Reputation: 1367
I am writing code for a windows application using vb.net. I want to open a text file under c:\
. If the file already exists I want to delete that file.
my code
-------
Dim file As String = "C:\test.txt"
If System.IO.File.Exists(file) Then
file.Remove(file)
Else
System.Diagnostics.Process.Start(file)
End If
I am getting the following error when I try to open that file.
error
-----
The system cannot find the file specified
Upvotes: 0
Views: 14471
Reputation: 25067
Apart from Konrad's point about trying to execute a file that you have just checked does not exist:
1) It's not a good idea to name your variable file
as it could get confused with System.IO.File.
2) It's File.Delete, not file.Remove - you're calling the String.Remove method because file
is a string. You should use Option Strict On because it would have caught that error for you.
3) On Windows Vista and later, you may not have write/delete access to C:.
Assuming you have write access to the directory C:\temp then this works:
Dim fyle As String = "C:\temp\test.txt"
If System.IO.File.Exists(fyle) Then
IO.File.Delete(fyle)
End If
IO.File.Create(fyle)
System.Diagnostics.Process.Start(fyle)
Upvotes: 2