Csharp/CSharp Tutorial/File Directory Stream/File
Содержание
Create the FileInfo class from the file selected in the OpenFileDialog
<source lang="csharp">using System; using System.Windows.Forms; using System.IO; class MainClass {
public static void Main() { OpenFileDialog dlgOpen = new OpenFileDialog(); if (dlgOpen.ShowDialog() == DialogResult.OK) { FileInfo fi = new FileInfo(dlgOpen.FileName); Console.WriteLine("Filename " + fi.FullName ); Console.WriteLine(" Created at " + fi.CreationTime ); Console.WriteLine(" Accessed at " + fi.LastAccessTime ); } }
}</source>
File.Exists
<source lang="csharp">using System; using System.IO; static class MainClass {
static void Main(string[] args) { Console.WriteLine(File.Exists("c:\\test.txt")); }
}</source>
True
File: GetCreationTime and GetLastAccessTime
<source lang="csharp">using System; using System.Windows.Forms; using System.IO; class MainClass {
public static void Main() { OpenFileDialog dlgOpen = new OpenFileDialog(); if (dlgOpen.ShowDialog() == DialogResult.OK) { string s = dlgOpen.FileName; Console.WriteLine("Filename " + s); Console.WriteLine(" Created at " + File.GetCreationTime(s)); Console.WriteLine(" Accessed at " + File.GetLastAccessTime(s)); } }
}</source>
File.ReadAllLines
<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.IO; class MainClass {
static void Main(string[] args) { StreamWriter writer = new StreamWriter(@"c:\myfile.txt"); for (int i = 0; i < 3; i++) { writer.Write(i.ToString()); } writer.Flush(); writer.Close(); foreach (string line in File.ReadAllLines(@"c:\myfile.txt")) { Console.WriteLine(line); } }
}</source>
012
File.WriteAllLines
<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.IO; class MainClass {
static void Main(string[] args) { string[] lines = new string[10]; for (int i = 0; i < 10; i++) { lines[i] = String.Format( "This is line number {0}", i); } File.WriteAllLines(@"c:\test.txt", lines); foreach (string line in File.ReadAllLines(@"c:\test.txt")) { Console.WriteLine(line); } }
}</source>
Key Members of the System.IO Namespace
<source lang="csharp">Nonabstract I/O Class Type Meaning BinaryReader BinaryWriter store and retrieve primitive data types (integers, Booleans, strings, and whatnot) as a binary value. BufferedStream temporary storage for a stream of bytes that may be committed to storage. Directory DirectoryInfo used to manipulate a directory structure. DriveInfo provides information for the drives. File FileInfo manipulate files. FileStream for random file access. FileSystemWatcher monitor the modification of a given external file. MemoryStream random access to streamed data stored in memory. Path performs operations on path information. StreamWriter StreamReader store and retrieve textual information to or from a file. StringWriter StringReader underlying storage is a string buffer rather than a physical file.</source>