学习.NET Winform开发 - 演示文件读写

学习.NET Winform开发 - 演示文件读写

撰写日期:2016/04/21
更新日期:2016/04/22
博客地址:http://www.cnblogs.com/gibbonnet/p/5418699.html

DemoFileIO.cs

基本操作

  • 新建文件: System.IO.FileStream
  • 读写文件: System.IO.StreamReader/StreamWriter
  • 设置编码: System.Text.Encoding
  • 处理异常: System.IO.Exception

进阶操作

  • 锁文件: System.IO.FileShare
  • 发现修改: System.IO.FileSystemWatcher
  • 文件唯一标识:System.IO.FileInfo
using System;
using System.IO;
using System.Text;
using System.Collections.Specialized;
using System.Windows.Forms;

namespace gibbon.learning.winform
{
    /**
     * DemoFileIO
     * 新建文件
     * 读写文件
     * 设置编码
     * 处理异常
     */
    public class DemoFileIO
    {
        /**
         * 将文件从UTF-8编码转换为Unicode编码
         */
        [STAThread]
        static void Main(string[] args)
        {
            string filePath = args[0];
            string outFilePath = args[1];

            const int MaxTextSize = 65535;

            FileStream fileStream;
            try
            {
                // 打开一个文件,如果不存在则创建
                fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            }
            catch(System.IO.DirectoryNotFoundException)
            {
                MessageBox.Show(String.Format("未能找到路径: {0}", filePath), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            // UTF8输入
            StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8);

            StringCollection stringCollection = new StringCollection();
            int noBytesRead = 0;
            string oneLine;
            // 一行一行地读入文件
            while((oneLine = streamReader.ReadLine())!=null) {
                noBytesRead += oneLine.Length;
                if(noBytesRead>MaxTextSize) break;
                stringCollection.Add(oneLine);
            }
            // 关闭文件
            streamReader.Close();

            string[] stringArray = new string[stringCollection.Count];
            stringCollection.CopyTo(stringArray,0);

            // 检测文件是否存在
            if(File.Exists(outFilePath)){
                if(MessageBox.Show(
                    String.Format("文件{0}已经存在,继续将覆盖该文件。是否继续?", outFilePath),
                    "提示",
                    MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2
                 ) == DialogResult.Cancel){
                     return;
                 }
            }

            // 创建输出文件,如果存在则覆盖
            FileStream outFileStream = new FileStream(outFilePath, FileMode.Create, FileAccess.Write);
            // Unicode输出
            StreamWriter outStreamWriter = new StreamWriter(outFileStream, Encoding.Unicode);

            // 逐行输出文件
            for(int i=0; i<stringArray.Length; i++) {
                outStreamWriter.WriteLine(stringArray[i]);
            }

            // 关闭输出文件
            outStreamWriter.Close();
        }
    }
}

控制台程序

Console类:https://msdn.microsoft.com/zh-cn/library/system.console(v=vs.110).aspx

读取命令行参数 string[] args

标准输入输出 Console.ReadLine(), WriteLine()

执行CMD命令:http://www.cnblogs.com/babycool/p/3570648.html

命名空间System.IO

FileStream: 为文件提供流,支持同步和异步的读写操作。

public FileStream(
	string path,
	FileMode mode,
	FileAccess access,
	FileShare share,
	int bufferSize,
	FileOptions options
)
public FileStream(
	string path,
	FileMode mode,
	FileSystemRights rights,
	FileShare share,
	int bufferSize,
	FileOptions options,
	FileSecurity fileSecurity
)

FileMode: 指定操作系统打开文件的方式

  • Append 如果存在文件,则追加;不存在,则创建;
  • Create 创建新文件,如果存在,则覆盖;
  • CreateNew 创建新文件,如果存在,则引发IOException
  • Open 打开文件,如果不存在,则引发FileNotFoundException
  • OpenOrCreate 打开文件,如果不存在,则创建;
  • Truncate 打开文件,该文件被打开时,将被截断为零字节大小。??不明白

FileAccess

  • Read 读文件
  • ReadWrite 读写文件
  • Write 写文件

FileShare: 枚举,定义常量,控制其他FileStream对于同一个文件所能具有的访问权。这些值可以按位与操作。

  • Delete 允许删除文件
  • Inheritable 使文件句柄可以有子进程继承,不支持Win32
  • None 拒绝共享当前文件
  • Read 允许后面的进程打开文件来读
  • ReadWrite 允许后面的进程打开文件读或写
  • Write 允许后面的进程打开文件来写

FileOptions:枚举,创建FileStream的高级选项

  • Asynchronous 异步读取和写入 ??不懂
  • DeleteOnClose 关闭即删除
  • Encrypted 文件是加密的
  • None
  • RandomAccess 随机访问文件
  • SequentialAccess 顺序访问文件
  • WriteThrough 指示系统通过任何中间缓存、直接写入磁盘

StreamReader/StreamWriter

StreamReader 构造函数

public StreamReader(
	Stream stream,
	Encoding encoding,
	bool detectEncodingFromByteOrderMarks,
	int bufferSize,
	bool leaveOpen
)

StreamWriter 构造函数

public StreamWriter(
	Stream stream,
	Encoding encoding,
	int bufferSize,
	bool leaveOpen
)

BinaryReader/BinaryWriter

文件修改检测:FileSystemWatcher

似乎只能以检测文件夹为单位检测,事件包括:Changed, Created, Deleted, Disposed, Error, Renamed

参考:http://blog.csdn.net/chen_zw/article/details/7916262

using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{

    public static void Main()
    {
    Run();

    }

    [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if(args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = args[1];
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch text files.
        watcher.Filter = "*.txt";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
}

文件唯一标识

利用 FileInfo.CreateTimeUTC.CreationTimeUtc.Ticks.ToString()
关于DataTime:http://www.cnblogs.com/Peter-Zhang/articles/1778143.html

using System;
using System.IO;

class ShowFileCreationTicks
{
    public static void Main(string[] args)
    {
        FileInfo fi = new FileInfo(args[0]);
        Console.WriteLine(fi.CreationTimeUtc.Ticks.ToString());
    }
}

测试:
连续创建文件:不同
移动文件:不改变
复制文件:改变

命名空间System.Text

System.Text命名空间包含代表ASCII和Unicode字符编码的类;包含虚基类用于将字符块转换为字节块,以及反过来转换;一个帮助类在不需要创建String实例的情况下操作和格式化String对象。

命名空间System.Collections

System.Collections命名空间包含定义对象各种集合的接口和类,例如列表、队列、字节数组、哈希表格和字典。

MessageBox类

public static DialogResult Show(
	string text,
	string caption,
	MessageBoxButtons buttons,
	MessageBoxIcon icon,
	MessageBoxDefaultButton defaultButton,
	MessageBoxOptions options,
	string helpFilePath,
	string keyword
)

展示信息框,带有特定的文本、标题、按钮、图标、默认按钮、选项、帮助按钮,使用指定的帮助文件和帮助关键字。

// 例子
// Display a message box. The Help button opens the Mspaint.chm Help file, 
// and the "mspaint.chm::/paint_brush.htm" Help keyword shows the 
// associated topic.
DialogResult r7 = MessageBox.Show ("Message with Help file and keyword.", 
                                   "Help Caption", MessageBoxButtons.OK, 
                                   MessageBoxIcon.Question, 
                                   MessageBoxDefaultButton.Button1, 0, 
                                   "mspaint.chm", 
                                   "mspaint.chm::/paint_brush.htm");

MessageBoxIcon:

  • Asterisk
  • Error
  • Exclamation
  • Hand
  • Information
  • None
  • Question
  • Stop
  • Warning
posted @ 2016-04-21 20:54  Gibbon  阅读(534)  评论(0编辑  收藏  举报