c# 使用FileStream打开并清空文件、将一文件内容另存为到新文件

来源:互联网 发布:淘宝客服话术大全砍价 编辑:程序博客网 时间:2024/05/18 04:00

*以下为使用FileStream方式打开并清空文件: 

FileStream fs = null;
            try
            {
                fs = new FileStream(m_LogFilePath, FileMode.Truncate, FileAccess.ReadWrite);

            }
            catch (Exception ex)
            {
                Trace.Write("清空日志文件失败:" + ex.Message);
            }
            finally
            {
                fs.Close();
            }

注意:对文件进行读写操作,最好都用try-catch。

          在使用FileMode.Truncate时,FileAccess不能使用FileAccess.Read;仔细想想也知道,此种模式其实,是需要先将文件中的内容清空。

 

*以下为将一文件内容另存为到新文件:

 SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "文本文件(*.txt)|*.txt";
            saveFileDialog.Title = "另存为";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = null;
                StreamWriter sw = null;
                StreamReader sr = null;
                try
                {
                    fs = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.ReadWrite);
                    fs.Close();

                    sr = new StreamReader(m_LogFilePath);//m_LogFilePath为需要另存为的文件的路径
                    sw = new StreamWriter(saveFileDialog.FileName);
                    sw.Write(sr.ReadToEnd());
                    sw.Flush();
                }
                catch (Exception ex)
                {
                    Trace.Write("清空日志文件失败:" + ex.Message);
                }
                finally
                {
                    if(fs!=null)
                        fs.Close();
                    sw.Close();
                    sr.Close();
                }
            }

0 0