sing System;
using System.Collections.Generic;
using System.Text;
//***********************
using System.Collections.Specialized;
using System.IO;
namespace FileOperate
{
public class FileOperate
{
/// <summary>
/// 读取字典文件,存于字典并返回
/// </summary>
/// <param name="filePath">字典文件路径</param>
/// <returns>返回字典</returns>
public StringCollection FileRead(string filePath)
{
//读文件
StreamReader din = new StreamReader(new FileStream(filePath, FileMode.Open), System.Text.Encoding.Default);
//StreamReader din = File.OpenText(filePath);
//读取的每一行
string str;
//字典
StringCollection st = new StringCollection();
//循环读取并存入字典
while ((str = din.ReadLine()) != null)
{
st.Add(str);
}
//关闭文件流
din.Close();
//返回字典
return st;
}
/// <summary>
/// 读取指定路径文章并以字符串输出
/// </summary>
/// <param name="filePath">文章路径</param>
/// <returns>文章字符串</returns>
public string FileReadString(string filePath)
{
//读文件
StreamReader din = new StreamReader(new FileStream(filePath, FileMode.Open), System.Text.Encoding.Default);
//StreamReader din = File.OpenText(filePath);
//存入字符串
string str = din.ReadToEnd();
//关闭文件流
din.Close();
//返回文件字符串
return str;
}
/// <summary>
/// 把指定字符串写入文件
/// </summary>
/// <param name="file">文件字符串</param>
/// <param name="filePath">要写入文件路径</param>
/// <returns>返回是否写入成功</returns>
public bool FileWrite(string file, string filePath)
{
bool isFileWrite = true;
try
{
//写入文件流
StreamWriter sw = new StreamWriter(new FileStream(filePath, FileMode.Create), System.Text.Encoding.Default);
//StreamWriter sw = new StreamWriter(filePath, true, System.Text.Encoding.Default);
//把字符串写入文件
sw.Write(file);
//关闭文件流
sw.Close();
}
catch (Exception ex)
{
isFileWrite = false;
throw ex;
}
//返回是否写入成功
return isFileWrite;
}
/// <summary>
/// 把指定字符串追加写入文件
/// </summary>
/// <param name="file">文件字符串</param>
/// <param name="filePath">要写入文件路径</param>
/// <returns>返回是否写入成功</returns>
public bool FileAppendWrite(string file, string filePath)
{
bool isFileWrite = true;
try
{
//写入文件流
StreamWriter sw = new StreamWriter(new FileStream(filePath, FileMode.Append), System.Text.Encoding.Default);
//把字符串追加写入文件
sw.Write(file);
//关闭文件流
sw.Close();
}
catch (Exception ex)
{
isFileWrite = false;
throw ex;
}
//返回是否写入成功
return isFileWrite;
}
/// <summary>
/// 替换文件中词典里包含的词
/// </summary>
/// <param name="dictionary">词典</param>
/// <param name="file">文件</param>
/// <returns>新的文件</returns>
public string FileCompare(StringCollection dictionary, string file)
{
try
{
foreach (string word in dictionary)
{
//如果文件包含词典里的词就把该词替换
if (file.Contains(word))
{
file= file.Replace(word, word +"// ");
}
}
}
catch (Exception ex)
{
throw ex;
}
//返回替换后的文件
return file;
}
}
}