checking files using c#
plz any one help i need code in c# for checking afile is exisisting if it exists display that file if does not exists create a file in any folder using c# its very urgent if any ine have htis in vb.net also u can give me thanks
AlanPosted Oct 7, 2007, 6:49 AM
You can use the System.IO.File.Exists() method to determine whether a file exists or not. See this link for examples of usage in both C# and VB.Net:
http://msdn2.microsoft.com/en-us/library/system.io.file.exists.aspx
Here's a console app in C# which does what you've specifically asked for:
// requires .NET 2.0 or later
using System;
using System.IO;
class Test
{
static void Main()
{
string filePath = @"c:\myfiles\somefile.txt"; // say
string[] lines;
if (File.Exists(filePath))
{
lines = File.ReadAllLines(filePath);
foreach(string line in lines)
Console.WriteLine(line);
}
else
{
lines = new string[2];
lines[0] = "Hello";
lines[1] = "From C# Corner";
File.WriteAllLines(filePath, lines);
}
}
}
In VB.Net, this would be:
' requires .NET 2.0 or later
Imports System
Imports System.IO
Class Test
Shared Sub Main()
Dim filePath As String = "c:\myfiles\somefile.txt" ' say
Dim lines As String()
If File.Exists(filePath)
lines = File.ReadAllLines(filePath)
For Each line As String In lines
Console.WriteLine(line)
Next
Else
lines = New String(2){}
lines(0) = "Hello"
lines(1) = "From C# Corner"
File.WriteAllLines(filePath, lines)
End If
End Sub
End Class