Csharp/CSharp Tutorial/File Directory Stream/FileInfo

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Create FileStream from FileInfo for reading

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo MyFiles = new FileInfo(@"c:\Testing.txt");
    FileStream MyFileStream1 = MyFiles.OpenRead();
    int MyBytes = MyFileStream1.ReadByte();
    MyFileStream1.Close();    
  }
}

Create FileStream from FileInfo for writing

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo MyFiles = new FileInfo(@"c:\Testing.txt");
    FileStream MyFileStream1 = MyFiles.OpenWrite();
    byte MyWriteByte = 100;
    MyFileStream1.WriteByte(MyWriteByte);
    
    MyFileStream1.Close();    
  }
}

Create StreamWriter from FileInfo

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo MyFile = new FileInfo(@"c:\Testing.txt");
    StreamWriter MyStreamWriter = MyFile.CreateText();
    MyStreamWriter.Write("a string");
    MyStreamWriter.Close();
    
  }
}

File Sorter

using System;
using System.IO;
using System.ruponentModel;
    class FileSorter{
        static void SortAndShowFiles(string title,Comparison<FileInfo> sortOrder){
            FileInfo[] files = new DirectoryInfo("C:\\").GetFiles();
            Array.Sort(files, sortOrder);
            Console.WriteLine(title);
            foreach (FileInfo file in files){
                Console.WriteLine("  {0} ({1} bytes)",file.Name, file.Length);
            }
        }
        static void Main(){
            SortAndShowFiles("Sorted by name:",delegate(FileInfo first, FileInfo second)
                { return first.Name.rupareTo(second.Name); }
            );
        }
    }

Open an existing file and return a FileStream

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo MyFile = new FileInfo(@"c:\Testing.txt");
    FileStream MyStream;
    MyStream = MyFile.Open(FileMode.Open, FileAccess.Read, FileShare.None);
  }
}

Show info on image types

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;

  class Program
  {
    static void Main(string[] args)
    {
      DirectoryInfo dir = new DirectoryInfo(@"C:\Windows\Web\Wallpaper");
      FileInfo[] imageFiles = dir.GetFiles("*.jpg");
      Console.WriteLine("Found {0} *.jpg files\n", imageFiles.Length);
      foreach (FileInfo f in imageFiles)
      {
        Console.WriteLine("File name: {0}", f.Name);
        Console.WriteLine("File size: {0}", f.Length);
        Console.WriteLine("Creation: {0}", f.CreationTime);
        Console.WriteLine("Attributes: {0}", f.Attributes);
      }
    }
  }