From Wrox Pro C# 2005 w/ .net 3.0 - ch. 24 System.MarshalByRefObject - base obj for classes that are remoteable - permits marshaling of data between application domains FileSystemInfo - base class represents any fso FileInfo and File - file DirectoryInfo and Directory - folder Path - static members to manipulate path names DriveInfo - drive Directory and File - never instantiated - one operation - provide path and fso each time - no overhead for instantiating a class DirectoryInfo and FileInfo - instantiated - multiple operations - provide path and fso one time - overhead of instantiating a class -- // these 2 chunks do the same thing FileInfo myFile = new FileInfo(@"c:\temp\readme.txt"); myFile.CopyTo(@"c:\temp\readmetoo.txt"); File.Copy(@"c:\temp\readme.txt", @"c:\temp\readmetoo.txt"); -- // make a folder DirectoryInfo myFolder = new DirectoryInfo(@"c:\temp\newfolder"); -- discover info - FileInfo and DirectoryInfo CreationTime DirectoryName (file) Parent (dir) Exists Extension FullName LastAccessTime LastWriteTime Name Root (dir) Length (file) -- fso methods -- Create() Delete() MoveTo() CopyTo() (file) GetDirectories() (dir) GetFiles() (dir) GetFileSystemInfos() (dir) -- //display the creation time of a file, //then changes it FileInfo test = new FileInfo(@"c:\temp\myFile.txt"); Console.WriteLine(test.Exists.ToString()); Console.WriteLine(test.CreationTime.ToString()); test.CreationTime = new DateTime(2000, 1, 1, 7, 30, 0); Console.WriteLine(test.CreationTime.ToString()); -- Console.WriteLine(Path.Combine(@"c:\temp", "readmeagain.txt"); -- ------------------- File Browse example ------------------- txtInput txtFolder btnDisplay btnUp lstFiles lstFolders txtFileName txtCreationTime txtLastAccessTime txtLastWriteTime txtFileSize using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; partial class Form1 :Form { #region Folder Content and File Details private string currentFolderPath; protected void ClearAllFields; { lstFiles.Items.Clear(); lstFolders.Items.Clear(); txtFolder.Text = ""; txtFileName.Text = ""; txtCreationTime.Text = ""; txtLastAccessTime.Text = ""; txtLastWriteTime.Text = ""; txtFileSize.Text = ""; txtNewPath.Text = ""; } void EnableMoveFeatures() } // enable move, copy, delete buttons txtNewPath.Text = thefile.FullName; txtNewPath.Enabled = true; btnCopyTo.Enabled = true; btnDelete.Enabled = true; btnMoveTo.Enabled = true; } void DisableMoveFeatures() { // disable move, copy, delete buttons txtNewPath.Text = ""; txtNewPath.Enabled = false; btnCopyTo.Enabled = false; btnDelete.Enabled = false; btnMoveTo.Enabled = false; } protected void DisplayFileInfo(string fileFullName) { FileInfo theFile(fileFullName); if (!theFile.Exist) { throw new FileNotFoundException("File not found: " + fileFullName); } txtFileName.Text = theFile.Name; txtCreationTime.Text = theFile.CreationTime.ToLongTimeString(); txtLastAccessTime.Text = theFile.LastAccessWriteTime.ToLongDateString(); txtLastWriteTime.Text = theFile.WriteTime.ToLongDateString(); txtFileSize.Text = theFile.Length.ToString() + " bytes"; // enable move, copy, delete buttons EnableMoveFeatures(); } protected void DisplayFolderList(string folderFullName) { FileInfo theFolder = new DirectoryInfo(folderFullName); if (!theFolder.Exist) { throw new DirectoryNotFoundException("Folder not found: ", folderFullName); } ClearAllFields(); DisableMoveFeatures(); txtFolder.Text = theFolder.FullName; currentFolderPath = theFolder.FullName; // list all subfolders in the folder foreach(DirectoryInfo nextFolder in theFolder.GetDirectories()) lstFolders.Items.Add(nextFolder.Name); // list all files in the folder foreach(FileInfo nextFile in theFolder.GetFiles()) lstFiles.Items.Add(nextFile.Name); } protected void OnDisplayClick(object sender, EventArgs e) { // is this a Folder, a File, or neither? try { string folderPath = txtInput.Text; DirectoryInfo theFolder = new DirectoryInfo(folderPath); if (theFolder.Exists) { DisplayFolderList(theFolder.FullName) return; } FileInfo theFile = new FileInfo(folderPath); if(theFile.Exists) { DisplayFolderList(theFile.Directory.FullName); int index = lstFiles.Items.IndexOf(theFile.Name); lstFiles.SetSelected(index, True); return; } throw new FileNotFoundException("There is no file or folder with this name:" + txtInput.Text); } catch(Exception ex) { MessageBox.Show(ex.Message); } } protected void OnListBoxFilesSelected(object sender, EventArgs e) { try { string selectedString = lstFiles.SelectedItem.ToString(); string fullFileName = Path.Combine(currentFolderPath, selectedString); DisplayFileInfo(fullFileName); } catch(Exception ex { MessageBox.Show(ex.Message); } } protected void OnListBoxFoldersSelected(object sender, EventArgs e) { try { string selectedString = lstFolders.SelectedItem.ToString(); string fullPathName = Path.Combine(currentFolderPath, selectedString); DisplayFolderList(fullPathName); } catch(Exception ex) { MessageBox.Show(ex.Message); } } protected void OnUpButtonClick(object sender, EventArgs e) { try { string folderPath = new FileInfo(currentFolderPath).DirectoryName; DisplayFolderList(folderPath); } catch(Exception ex) { MessageBox.Show(ex.Message); } } #endregion #region File Properties and Movement protected void OnDeleteButtonClick(object sender, EventArgs e) { try { string filePath = Path.Combine(currentFolderPath, txtFileName.Text); string query = "Really delete the file \n" + filePath + " ?"; if (MessageBox.Show(query, "Delete File?", MessageBoxButtons.YesNo) == DialogResult.Yes) { File.Delete(filePath); DisplayFolderList(currentFolderPath); } catch(Exception ex) { MessageBox.Show("Unable to delete file. The following exception occurred: \n" + ex.Message, "Failed"); } } } protected void OnMoveButtonClick(object sender, EventArgs e) { try { string filePath = Path.Combine(currentFolderPath, txtFileName.Text); string query = "Really move the file \n" + filePath + " \n to " txtNewPath.Text + "?"; if (MessageBox.Show(query, "Move File?", MessageBoxButtons.YesNo) == DialogResult.Yes) { File.Move(filePath, txtNewPath.Text); DisplayFolderList(currentFolderPath); } catch(Exception ex) { MessageBox.Show("Unable to move file. The following exception occurred: \n" + ex.Message, "Failed"); } } } protected void OnCopyButtonClick(object sender, EventArgs e) { try { string filePath = Path.Combine(currentFolderPath, txtFileName.Text); string query = "Really copy the file \n" + filePath + " \n to " txtNewPath.Text + "?"; if (MessageBox.Show(query, "Copy File?", MessageBoxButtons.YesNo) == DialogResult.Yes) { File.Copy(filePath, txtNewPath.Text); DisplayFolderList(currentFolderPath); } catch(Exception ex) { MessageBox.Show("Unable to copy file. The following exception occurred: \n" + ex.Message, "Failed"); } } } #endregion } //end of class ------------------------ File Reading and Writing ------------------------ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; partial class Form2 :Form { #region File Reading and Writing private void btnSelect_Click(object sender, EventArgs e) { private void btnSource_Click(object sender, EventArgs e) { //Stream myStream = null; OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\tmp"; openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { txtSource.Text = openFileDialog1.FileName; } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } } private void btnReadAll_Click(object sender, EventArgs e) { txtContents.Text = File.ReadAll(txtSource.Text); } private void btnReadAllBytes_Click(object sender, EventArgs e) { txtContents.Text = File.ReadAllBytes(txtSource.Text); } private void btnWriteAllLines_Click(object sender, EventArgs e) { File.WriteAllLines(txtSource.Text, listOfFileNames); } void DisplayFileBytes() { int nCols = 16; FileStream inStream = new FileStream(txtSource.Text, FileMode.Open, FileAccess.Read); //open for reading long nBytesToRead = inStream.Length; // 65,536 is the max length the textbox can hold if (nBytesToRead > 65536/4 ) // we're showing characters for every byte nBytesToRead = 65536/4; // so cap it. int nLines = (int)(nBytesToRead/nCols) + 1; string [] lines = new string[nLines]; int nBytesRead = 0; for (int i = 0; i < nLines; i++) { StringBuilder nextLine = new StringBuilder(); nextLine.Capacity = 4 * nCols; for (int j = 0; j < nCols; j++) { int nextByte = inStream.ReadByte(); nBytesRead++; if (nextByte < 0 || nBytesRead > 65536) break; char nextChar = (char)nextByte; if (nextChar < 16) nextLine.Append(" x0" + string.Format("{0,1:X}", (int)nextChar)); else if (char.IsLetterOrDigit(nextChar) || char.IsPunctuation(nextChar)) nextLine.Append(" " + string.Format("{0,2:X}", (int)nextChar); } lines[i] = nextLine.ToString(); } inStream.Close(); this.txtContents.Lines = lines; } #region Gratuitous Syntax Examples void StreamReaderSyntax() { StreamReader sr = new StreamReader(txtSource.Text); //could also be: ASCII, Unicode, UTF7, UTF8, UTF32, BigEndianUnicode StreamReader sr = new StreamReader(txtSource.Text, Encoding.UTF8); // allows you to specify -whether to create the file, and -share permissions FileStream fs = new FileStream(txtSource.Text, FileMode.Open, FileAccess.Read, FileShare.None); StreamReader sr = new StreamReader(fs); FileInfo myFile = new FileInfo(txtSource.Text); StreamReader sr = myFile.OpenText(); sr.Close(); string nextLine = sr.ReadLine(); string restOfStream = sr.ReadToEnd(); int nextChar = sr.Read(); // to read 100 characters in int nChars = 100; char [] charArray = new char[nChars]; int nCharsRead = sr.Read(charArray, 0, nChars); } void StreamWriterSyntax() { StreamWriter sw = StreamWriter(txtSource.Text); StreamWriter sw = StreamWriter(txtSource.Text, true, Encoding.ASCII); FileStream fs = new FileStream(txtSource.Text, FileMode.CreateNew, FileAccess.Write, FileShare.Read); StreamWriter sw = new StreamWriter(fs); // create a new file and start writing to it FileInfo myFile = new FileINfo(txtSource.Text); StreamWriter sw = MyFile.CreateText(); sw.Close(); // write a string string nextLine = "Groovy Line"; sw.Write(nextLine); // write a character array char [] charArray = new char[100]; // initialize them sw.Write(charArray); // write some of the characters from an array int nCharsToWrite = 50; int startAtLocation = 25; char [] charArray = new [100]; // initialize them sw.Write(charArray, startAtLocation, nCharToWrite); } #endregion } //end of Form2 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; partial class Form3 :Form { private void btnSource_Click(object sender, EventArgs e) { //Stream myStream = null; OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\tmp"; openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { txtSource.Text = openFileDialog1.FileName; } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } } void DisplayFile() { StringCollection linesCollection = ReadFileIntoStringCollection(); string [] linesArray = new string[linesCollection.Count]; linesCollection.CopyTo(linesArray, 0); this.txtContent.Lines = linesArray; } // count characters read in so you don't exceed the capacity of the textbox StringCollection ReadFileIntoStringCollection() { const in MaxBytes = 65536; StreamReader sr = new StreamReader(txtSource.Text); StringCollection result = new StringCollection(); int nBytesRead = 0; string nextLine; while ((nextLine = sr.ReadLine()) != null) { nBytesRead += nextLine.Length; if (nBytesRead > MaxBytes) break; result.Add(nextLine); } sr.Close(); return result; } void SaveFile() { StreamWriter sw new StreamWriter(txtSource.Text, false, Encoding.Unicode); foreach (string line in txtContent.Lines) sw.WriteLine(line); sw.Close(); } } // end of Form3 ---------- Drive Info ---------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace DriveInfo { partial class Form1 :Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { DriveInfo[] di = DriveInfo.GetDrives(); foreach (DriveInfo itemDrive in di) { lstDrives.Items.Add(itemDrive.Name); } } private void lstDrives_SelectedIndexChanged(object sender, EventArgs e) { DriveInfo di = new DriveInfo(lstDrives.SelectedItem.ToString()); MessageBox.Show( "Available Free Space: \t" + di.AvailableFreeSpace + "\n" + "Drive Format: \t" + di.DriveFormat + "\n" + "Drive Type: \t" + di.DriveType + "\n" + "Is Ready: \t" + di.IsReady.ToString() + "\n" + "Name: \t" + di.Name + "\n" + "Root Directory: \t" + di.RootDirectory + "\n" + "ToString Value: \t" + di.ToString() + "\n" + "Total Free Space: \t" + di.TotalFreeSpace + "\n" + "Total Size: \t" + di.TotalSize + "\n" + "Volume Label: \t" + di.VolumeLabel.ToString(), di.Name + " DRIVE INFO"); } } // end of Form1 }