The .NET Framework provides four basic classes for retrieving file system information. They are all located in the System.IO namespace.They include the following:
· Directory and File. These classes provide static methods that allow you to retrieve information about any files and directories that are visible from your server.
· DirectoryInfo and FileInfo. These classes use similar instance methods and properties to retrieve the same sort of information.
string directoryName = @”c:\Temp”;
// Retrieve the list of files, and display it in the page.
string[] fileList = Directory.GetFiles(ftpDirectory);
foreach (string file in fileList)
{
lstFiles.Items.Add(file);
}
DirectoryInfo and FileInfo:
DirectoryInfo myDirectory = new DirectoryInfo(@”c:\Temp”);
FileInfo myFile = new FileInfo(@”c:\Temp\readme.txt”);
You can create directory or file if doesn’t exist.
myDirectory.Create();
FileStream stream = myFile.Create();
stream.Close();
We can filter files using wildcards.
DirectoryInfo dir = new DirectoryInfo(@”c:\temp”);
// Get all the files with the .txt extesion.
FileInfo[] files = dir.GetFiles(“*.txt”);
We can retrieve full path of either file or directory using Path class.
String filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,txtfilename);
We can get particular file version using FileVersionInfo.
FileVersionInfo info = FileVersionInfo.GetVersionInfo((string)path);
Streams:
Streams are used to represent data in a memory buffers, data that’s being retrieved over a network.
FileStream fileStream = null;
try
{
fileStream = new FileStream(fileName, FileMode.Create);
fileStream.Write(bytes);
}
finally
{
if (fileStream != null) fileStream.Close();
}
We can create txt files using streamwriter,
string fileName = “sample.txt”;
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
StreamWriter w = new StreamWriter(fs);
w.WriteLine(DateTime.Now);
w.WriteLine(message);
w.Close();
}
Hope this helps for understanding files and streams.
Happy Coding.
Comments are closed.