C#基础:文件的读写

FileStream读写文件示例:

FileStream读:

  1.          byte[] byteData = new byte[200];
  2.          char[] charData = new char[200];
  3.          try
  4.          {
  5. // 读取当前文件..表示上级目录
  6.             FileStream aFile = new FileStream("../../Program.cs", FileMode.Open);
  7. //查找并从指定位置读取
  8.             aFile.Seek(174, SeekOrigin.Begin);
  9.             aFile.Read(byteData, 0, 200);
  10.          }
  11.          catch (IOException e)
  12.          {
  13.             WriteLine("An IO exception has been thrown!");
  14.             WriteLine(e.ToString());
  15.             ReadKey();
  16.             return;
  17.          }
  18. //编码
  19.          Decoder d = Encoding.UTF8.GetDecoder();
  20.          d.GetChars(byteData, 0, byteData.Length, charData, 0);
  21.          WriteLine(charData);
  22.          ReadKey();

StreamFile写:

  1.          byte[] byteData;
  2.          char[] charData;
  3.          try
  4.          {
  5. //打开文件,如果没有就创建新的
  6.             FileStream aFile = new FileStream("Temp.txt", FileMode.Create);
  7.             charData = "My pink half of the drainpipe.".ToCharArray();
  8.             byteData = new byte[charData.Length];
  9. //编码
  10.             Encoder e = Encoding.UTF8.GetEncoder();
  11.             e.GetBytes(charData, 0, charData.Length, byteData, 0, true);
  12. //查找位置,写入 
  13.             aFile.Seek(0, SeekOrigin.Begin);
  14.             aFile.Write(byteData, 0, byteData.Length);
  15.             ReadKey();
  16.          }
  17.          catch (IOException ex)
  18.          {
  19.             WriteLine("An IO exception has been thrown!");
  20.             WriteLine(ex.ToString());
  21.             ReadKey();
  22.             return;
  23.          }

StreamReader

  1.         string line;
  2.          try
  3.          {
  4.  //        用FileStream对象打开文件
  5.             FileStream aFile = new FileStream("Log.txt", FileMode.Open);
  6. //         用StreamReader对象读取文件
  7.            StreamReader sr = new StreamReader(aFile);
  8.             line = sr.ReadLine();
  9.             // Read data in line by line.
  10.             while (line != null)
  11.             {
  12.                WriteLine(line);
  13.                line = sr.ReadLine();
  14.             }
  15.             sr.Close();
  16.          }
  17.          catch (IOException e)
  18.          {
  19.             WriteLine("An IO exception has been thrown!");
  20.             WriteLine(e.ToString());
  21.          }

StreamWriter

  1. try
  2.          {
  3. //         FileStream对象打开文件
  4.             FileStream aFile = new FileStream("Log.txt", FileMode.OpenOrCreate);
  5. //          StreamWriter对象写入文件
  6.             StreamWriter sw = new StreamWriter(aFile);
  7.             bool truth = true;
  8.             // Write data to file.
  9.             sw.WriteLine("Hello to you.");
  10. //                                  文件写入的时间
  11.             sw.WriteLine($"It is now {DateTime.Now.ToLongDateString()} and things are looking good.");
  12.             sw.Write("More than that,");
  13.             sw.Write($" it's {truth} that C# is fun.");
  14.             sw.Close();
  15.          }
  16.          catch(IOException e)
  17.          {
  18.             WriteLine("An IO exception has been thrown!");
  19.             WriteLine(e.ToString());
  20.             ReadLine();
  21.             return;
  22.          }

GZipStream 读写压缩文件示例:

  1. static void SaveCompressedFile(string filename, string data)//保存
  2.       {
  3.          FileStream fileStream =
  4.             new FileStream(filename, FileMode.Create, FileAccess.Write);
  5. //压缩
  6.          GZipStream compressionStream =
  7.             new GZipStream(fileStream, CompressionMode.Compress);
  8.          StreamWriter writer = new StreamWriter(compressionStream);
  9.          writer.Write(data);
  10.          writer.Close();
  11.       }
  12.       static string LoadCompressedFile(string filename)//加载
  13.       {
  14.          FileStream fileStream =
  15.             new FileStream(filename, FileMode.Open, FileAccess.Read);
  16. //解压
  17.          GZipStream compressionStream =
  18.             new GZipStream(fileStream, CompressionMode.Decompress);
  19.          StreamReader reader = new StreamReader(compressionStream);
  20.          string data = reader.ReadToEnd();
  21.          reader.Close();
  22.          return data;
  23.       }
  24.       static void Main(string[] args)
  25.       {
  26.          try
  27.          {
  28.             string filename = "fileStream.txt";
  29.             WriteLine(//using static System.Console
  30.                "Enter a string to compress (will be repeated 100 times):");
  31.             string sourceString = ReadLine();
  32.             StringBuilder sourceStringMultiplier =
  33.                new StringBuilder(sourceString.Length * 100);
  34.             for (int i = 0; i < 100; i++)
  35.             {
  36.                sourceStringMultiplier.Append(sourceString);
  37.             }
  38.             sourceString = sourceStringMultiplier.ToString();
  39.             WriteLine($"Source data is {sourceString.Length} bytes long.");
  40.             SaveCompressedFile(filename, sourceString);
  41.             WriteLine($"\nData saved to {filename}.");
  42.             FileInfo compressedFileData = new FileInfo(filename);
  43.             WriteLine($"Compressed file is {compressedFileData.Length} bytes long.");
  44.             string recoveredString = LoadCompressedFile(filename);
  45.             recoveredString = recoveredString.Substring(
  46.                0, recoveredString.Length / 100);
  47.             WriteLine($"\nRecovered data: {recoveredString}");
  48.             ReadKey();
  49.          }
  50.          catch (IOException ex)
  51.          {
  52.             WriteLine("An IO exception has been thrown!");
  53.             WriteLine(ex.ToString());
  54.             ReadKey();
  55.          }
  56.       }

FileSystem'Watcher监控文件系统:

    简单的Design界面如下:

  1.         <Grid>
  2.     <Grid.RowDefinitions>
  3.       <RowDefinition Height="Auto" />
  4.       <RowDefinition Height="Auto" />
  5.       <RowDefinition />
  6.     </Grid.RowDefinitions>
  7.     <Grid Margin="4">
  8.       <Grid.ColumnDefinitions>
  9.         <ColumnDefinition />
  10.         <ColumnDefinition Width="Auto" />
  11.       </Grid.ColumnDefinitions>
  12.       <TextBox Name="LocationBox" TextChanged="LocationBox_TextChanged" />//显示文件名字
  13.       <Button Name="BrowseButton" Grid.Column="1" Margin="4,0,0,0" Content="Browse..." Click="BrowseButton_Click" />//浏览文件button
  14.     </Grid>
  15.     <Button Name="WatchButton" Content="Watch!" Margin="4" Grid.Row="1" Click="WatchButton_Click" IsEnabled="False" />//监控button
  16.     <ListBox Name="WatchOutput" Margin="4" Grid.Row="2" />//文件更改时显示
  17.   </Grid>

    代码隐藏文件如下:

  1.  private FileSystemWatcher watcher;
  2.       public MainWindow()
  3.       {
  4.          InitializeComponent();
  5.          watcher = new FileSystemWatcher();
  6.          watcher.Deleted += (s, e) =>           //删除
  7.             AddMessage($"File: {e.FullPath} Deleted");
  8.          watcher.Renamed += (s, e) =>        //重命名
  9.             AddMessage($"File renamed from {e.OldName} to {e.FullPath}");
  10.          watcher.Changed += (s, e) =>        //更改内容
  11.             AddMessage($"File: {e.FullPath} {e.ChangeType.ToString()}");
  12.          watcher.Created += (s, e) =>          //创建
  13.             AddMessage($"File: {e.FullPath} Created");
  14.       }
  15.       private void AddMessage(string message)
  16.       {
  17.          Dispatcher.BeginInvoke(new Action(
  18.             () => WatchOutput.Items.Insert(
  19.                0, message)));
  20.       }
  21.       private void BrowseButton_Click(object sender, RoutedEventArgs e)//浏览button的点击事件,打开windows浏览文件对话框
  22.       {
  23.          OpenFileDialog dialog = new OpenFileDialog();
  24.          if (dialog.ShowDialog(this) == true)
  25.          {
  26.             LocationBox.Text = dialog.FileName;
  27.          }
  28.       }
  29.       private void LocationBox_TextChanged(object sender, TextChangedEventArgs e)//文本更改事件
  30.       {
  31.          WatchButton.IsEnabled = !string.IsNullOrEmpty(LocationBox.Text);
  32.       }
  33.       private void WatchButton_Click(object sender, RoutedEventArgs e)//监控button点击事件,开始监控
  34.       {
  35.          watcher.Path = System.IO.Path.GetDirectoryName(LocationBox.Text);
  36.          watcher.Filter = System.IO.Path.GetFileName(LocationBox.Text);
  37.          watcher.NotifyFilter = NotifyFilters.LastWrite |
  38.             NotifyFilters.FileName | NotifyFilters.Size;
  39.          AddMessage("Watching " + LocationBox.Text);
  40.          // Begin watching.
  41.          watcher.EnableRaisingEvents = true;
  42.       }
  43.    }

猜你喜欢

转载自blog.csdn.net/QQhelphelp/article/details/86502773