C#文件操作

  • 窗口下目标文件选择
  • 窗口下文件保存路径选择
  • 文件流读、写操作
  • 字符串处理

1.窗口下目标文件选择

有些时候我们为了将要打开的目标文件作为一个参数传给程序,可以在WPF中使用Winform中相应的类进行操作:
a.在项目中添加引用: System.Windows.Forms
b.使用其中的OpenFileDialog类

System.Windows.Forms.OpenFileDialog openFileDialog_LogFile = new System.Windows.Forms.OpenFileDialog();
            openFileDialog_LogFile.Title = "Please select target log file:";
            openFileDialog_LogFile.Filter = "(*.txt)|*.txt|所有文件(*.*)|*.*”";
            if (openFileDialog_LogFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileIO.inputFileName = openFileDialog_LogFile.FileName;
                LoadedLogFileTextBox.Text = fileIO.inputFileName;
            }

其中:Filter属性可以对目标文件类型进行筛选

2. 窗口下输出文件路径选择

文件操作中经常需要选择文件保存的路径,可以在WPF中使用Winform中相应的类进行操作:
a. 在项目中添加引用: System.Windows.Forms
b. 使用其中的FolderBrowserDialog类

System.Windows.Forms.FolderBrowserDialog saveFileFolderDialog_OutputPath = new System.Windows.Forms.FolderBrowserDialog();
            saveFileFolderDialog_OutputPath.Description = "Please select processed output file path:";
            if (saveFileFolderDialog_OutputPath.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                fileIO.outputFilePath = saveFileFolderDialog_OutputPath.SelectedPath;
                OutputFilePathTextBox.Text = fileIO.outputFilePath;
            }

3.文件流使用

可以使用C#对log文件中的关键信息进行提取,在命名空间System.IO中有对应的文件读写类可以执行相应的操作。

 System.IO.FileStream inputFileStream = new System.IO.FileStream(IO.inputFileName, System.IO.FileMode.Open);
            System.IO.StreamReader inputFileStreamReader = new System.IO.StreamReader(inputFileStream);
            System.IO.FileStream outputFileStream = new System.IO.FileStream(outputName, System.IO.FileMode.Create);
            System.IO.StreamWriter outputFileStreamWriter = new System.IO.StreamWriter(outputFileStream, Encoding.GetEncoding("gb2312"));

首先生成FileStream的的对象,再通过FileStream的对象生成StreamReader或StreamWriter的对象,StreamReader读取文件的信息,StreamWriter往文件里写内容

inputFileStreamReader.Close();
outputFileStreamWriter.Close();

文件读、写完毕后通过对应的Close()方法关闭文件流

4.字符串处理

首先,读取一行内容:

string readLine = inputFileStreamReader.ReadLine();

对读取的内容使用给定的字符进行分裂,如空格,逗号等

 string[] dataSplit = readLine.Split(':');

分裂完后会返回一个字符串,根据字符串索引即可得到有用信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值