具体代码如下:
private void Form3_Load(object sender, EventArgs e)
{
DataTable datatable = FindFile(comboBox1);
dataGridView1.DataSource = datatable;
}
//参数为指定的目录
public DataTable FindFile(ComboBox comboBox)
{
DataTable db = new DataTable();
db.Columns.Add("ID", System.Type.GetType("System.String"));
db.Columns.Add("Name", System.Type.GetType("System.String"));
string Path = Application.StartupPath + @"\File";
//在指定目录及子目录下查找文件,在listBox1中列出子目录及文件
DirectoryInfo Dir = new DirectoryInfo(Path);
try
{
int i = 1;
comboBox.Items.Clear();
foreach (FileInfo f in Dir.GetFiles("*.txt")) //查找文件
{
DataRow newdr = db.NewRow();
comboBox.Items.Add(f.ToString()); //向ComboBox中填加文件名
newdr[0] = i;
newdr[1] = f.ToString();
db.Rows.Add(newdr);
i++;
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message);
}
return db;
}
private void dataGridView1_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
if (dataGridView1.CurrentRow != null)
{
int Crows = dataGridView1.CurrentRow.Index;
string fileName = dataGridView1.Rows[Crows].Cells["FileName"].Value.ToString();
ReadData(fileName);
if (txtTitle.Text.Trim() != "")
{
OutMsg(rTxt, txtTitle.Text.Trim(), System.Drawing.Color.Red);
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string fileName = comboBox1.SelectedItem.ToString();
ReadData(fileName);
if (txtTitle.Text.Trim() != "")
{
OutMsg(rTxt, txtTitle.Text.Trim(), System.Drawing.Color.Red);
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (txtTitle.Text.Trim() != "")
{
DataTable datatable = SearchFile(comboBox1, txtTitle.Text.Trim());
dataGridView1.DataSource = datatable;
}
else
{
MessageBox.Show("请输入要查询的内容!");
}
}
private DataTable SearchFile(ComboBox comboBox, string Txt)
{
DataTable db = new DataTable();
db.Columns.Add("ID", System.Type.GetType("System.String"));
db.Columns.Add("Name", System.Type.GetType("System.String"));
string Path = Application.StartupPath + @"\File";
//在指定目录及子目录下查找文件,在listBox1中列出子目录及文件
DirectoryInfo Dir = new DirectoryInfo(Path);
try
{
int i = 1;
comboBox.Items.Clear();
foreach (FileInfo f in Dir.GetFiles("*.txt")) //查找文件
{
if (SearchData(f, Txt) || f.ToString().IndexOf(Txt) != -1)
{
DataRow newdr = db.NewRow();
comboBox.Items.Add(f.ToString()); //向ComboBox中填加文件名
newdr[0] = i;
newdr[1] = f.ToString();
db.Rows.Add(newdr);
i++;
}
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message);
}
return db;
}
public bool SearchData(FileInfo file, string Txt)
{
string Path = Application.StartupPath + @"\File" + "\\" + file;
txtPath.Text = Path.ToString();
Encoding fileEncoding = GetEncoding(Path);
StreamReader sr = new StreamReader(Path, fileEncoding);//用该编码创建StreamReader
string strLine = sr.ReadLine();//读取文件中的一行
while (strLine != null)//判断是否为空,表示到文件最后一行了
{
if (strLine.IndexOf(Txt) != -1)
{
sr.Close();
return true;
}
strLine = sr.ReadLine();
}
//关闭文件,注意顺序,先对文件内部进行关闭,然后才是文件~
sr.Close();
return false;
}
private void OutMsg(RichTextBox rtb, string msg, Color color)
{
int leng = rtb.Lines.Length;
string[] line = new string[leng];
for (int i = 0; i < leng; i++)
{
line[i] = rtb.Lines[i];
}
RichTextBox rb = new RichTextBox();
rtb.Text = "";
for (int i = 0; i < leng; i++)
{
if (line[i].IndexOf(msg) != -1)
{
rtb.SelectionStart = rtb.Text.Length;//设置插入符位置为文本框末
rtb.SelectionColor = color;//设置文本颜色
if (i == leng - 1)
{
rtb.AppendText(line[i]);
}
else
{
rtb.AppendText(line[i] + "\r\n"); //输出文本,换行
}
rtb.ScrollToCaret();//滚动条滚到到最新插入行
}
else
{
if (i == leng - 1)
{
rtb.AppendText(line[i]);
}
else
{
rtb.AppendText(line[i] + "\r\n"); //输出文本,换行
}
}
}
rtb.Text.Trim();
}
private Color ReturnColorFromString(string color)
{
string alpha = color.Substring(0, 2);
string red = color.Substring(2, 2);
string green = color.Substring(4, 2);
string blue = color.Substring(6, 2);
byte alphaByte = Convert.ToByte(alpha, 16);
byte redByte = Convert.ToByte(red, 16);
byte greenByte = Convert.ToByte(green, 16);
byte blueByte = Convert.ToByte(blue, 16);
return Color.FromArgb(alphaByte, redByte, greenByte, blueByte);
}
private void btnAddNew_Click(object sender, EventArgs e)
{
DialogResult ds = MessageBox.Show("确定要新增文件吗?", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ds == DialogResult.Yes)
{
AddNewFile();
Form3_Load(sender, e);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (rTxt.Text.Trim() != "")
{
SaveToTxtFile();
}
else
{
MessageBox.Show("请选择需要保持的txt文件!");
}
}
private void btnAddSave_Click(object sender, EventArgs e)
{
if (rTxt.Text.Trim() != "")
{
SavefileAs();
SaveToTxtFile();
Form3_Load(sender, e);
}
else
{
MessageBox.Show("文件内容为空,不能保持,请先输入内容!");
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
if (dataGridView1.CurrentRow != null)
{
DialogResult ds = MessageBox.Show("确定要删除该文件吗?", "操作提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ds == DialogResult.Yes)
{
int Crows = dataGridView1.CurrentRow.Index;
string fileName = dataGridView1.Rows[Crows].Cells["FileName"].Value.ToString();
DeleteFile(fileName);
rTxt.Text = "";
Form3_Load(sender, e);
}
}
}
}
// ReadData 方法
public void ReadData(string fileName)
{
string Path = Application.StartupPath + @"\File" + "\\" + fileName;
txtPath.Text = Path.ToString();
Encoding fileEncoding = GetEncoding(Path);
StreamReader sr = new StreamReader(Path, fileEncoding);//用该编码创建StreamReader
string str1 = "";
string strLine = sr.ReadLine();//读取文件中的一行
while (strLine != null)//判断是否为空,表示到文件最后一行了
{
if (str1 != "")
{
str1 = str1 + "\r\n" + strLine;
}
else
{
str1 = strLine;
}
strLine = sr.ReadLine();
}
//关闭文件,注意顺序,先对文件内部进行关闭,然后才是文件~
sr.Close();
rTxt.Text = str1.ToString();
}
/// <summary>
/// 取得一个文本文件的编码方式。如果无法在文件头部找到有效的前导符,Encoding.Default将被返回。
/// </summary>
/// <param name="fileName">文件名。</param>
/// <returns></returns>
public static Encoding GetEncoding(string fileName)
{
return GetEncoding(fileName, Encoding.Default);
}
/// <summary>
/// 取得一个文本文件流的编码方式。
/// </summary>
/// <param name="stream">文本文件流。</param>
/// <returns></returns>
public static Encoding GetEncoding(FileStream stream)
{
return GetEncoding(stream, Encoding.Default);
}
/// <summary>
/// 取得一个文本文件的编码方式。
/// </summary>
/// <param name="fileName">文件名。</param>
/// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
/// <returns></returns>
public static Encoding GetEncoding(string fileName, Encoding defaultEncoding)
{
FileStream fs = new FileStream(fileName, FileMode.Open);
Encoding targetEncoding = GetEncoding(fs, defaultEncoding);
fs.Close();
return targetEncoding;
}
/// <summary>
/// 取得一个文本文件流的编码方式。
/// </summary>
/// <param name="stream">文本文件流。</param>
/// <param name="defaultEncoding">默认编码方式。当该方法无法从文件的头部取得有效的前导符时,将返回该编码方式。</param>
/// <returns></returns>
public static Encoding GetEncoding(FileStream stream, Encoding defaultEncoding)
{
Encoding targetEncoding = defaultEncoding;
if (stream != null && stream.Length >= 2)
{
//保存文件流的前4个字节
byte byte1 = 0;
byte byte2 = 0;
byte byte3 = 0;
byte byte4 = 0;
//保存当前Seek位置
long origPos = stream.Seek(0, SeekOrigin.Begin);
stream.Seek(0, SeekOrigin.Begin);
int nByte = stream.ReadByte();
byte1 = Convert.ToByte(nByte);
byte2 = Convert.ToByte(stream.ReadByte());
if (stream.Length >= 3)
{
byte3 = Convert.ToByte(stream.ReadByte());
}
if (stream.Length >= 4)
{
byte4 = Convert.ToByte(stream.ReadByte());
}
//根据文件流的前4个字节判断Encoding
//Unicode {0xFF, 0xFE};
//BE-Unicode {0xFE, 0xFF};
//UTF8 = {0xEF, 0xBB, 0xBF};
if (byte1 == 0xFE && byte2 == 0xFF)//UnicodeBe
{
targetEncoding = Encoding.BigEndianUnicode;
}
if (byte1 == 0xFF && byte2 == 0xFE && byte3 != 0xFF)//Unicode
{
targetEncoding = Encoding.Unicode;
}
if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF)//UTF8
{
targetEncoding = Encoding.UTF8;
}
//恢复Seek位置
stream.Seek(origPos, SeekOrigin.Begin);
}
return targetEncoding;
}
/// <summary>
/// 另存为
/// </summary>
private void SavefileAs()
{
SaveFileDialog savefile = new SaveFileDialog();
//提示用户选择保存文件(默认为桌面)
savefile.InitialDirectory = Application.StartupPath + @"\File";
//打开文件的初始目录
savefile.Filter = "文本文件(*.txt)|";
savefile.FileName = "Text";
//格式转换如此简单
savefile.DefaultExt = ".txt";
//设置或获取文件后缀
DialogResult dr = savefile.ShowDialog();
if (dr == DialogResult.OK)
{
String filePath = savefile.FileName.ToString();
txtPath.Text = filePath.ToString();
}
}
/// <summary>
/// 保存文件
/// </summary>
private void SaveToTxtFile()
{
try
{
//int buffer = 1024;
//创建一个文件流,用以写入或者创建一个StreamWriter
//FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
//通过指定字符编码方式可以实现对汉字的支持,否则在用记事本打开查看会出现乱码
/*改函数很重要由于要将修改的内容覆盖原来的文件内容故设第二个参数为false,
同时还不能用其他类如FileString来操作文件(多线程占用,不能覆盖修改文件)
* 例如:new StreamWriter(fs, true, Encoding.GetEncoding("GB2312"));是错误的*/
StreamWriter m_streamWriter = new StreamWriter(txtPath.Text, false, Encoding.GetEncoding("GB2312"));
m_streamWriter.Flush();
// 使用StreamWriter来往文件中写入内容
m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);
// 把richTextBox1中的内容写入文件
m_streamWriter.Write(rTxt.Text);
//关闭此文件
m_streamWriter.Flush();
m_streamWriter.Close();
MessageBox.Show("保存成功!");
}
catch (Exception ex)
{
MessageBox.Show("保存错误!请重试!错误信息:" + ex.Message); return;
}
}
/// <summary>
/// 新增
/// </summary>
private void AddNewFile()
{
SaveFileDialog savefile = new SaveFileDialog();
//提示用户选择保存文件(默认为桌面)
savefile.InitialDirectory = Application.StartupPath + @"\File";
//打开文件的初始目录
savefile.Filter = "文本文件(*.txt)|";
savefile.FileName = "Text";
//格式转换如此简单
savefile.DefaultExt = ".txt";
//设置或获取文件后缀
DialogResult dr = savefile.ShowDialog();
if (dr == DialogResult.OK)
{
String filePath = savefile.FileName.ToString();
try
{
if (!File.Exists(filePath))
{
FileStream fs1 = File.Create(filePath);
fs1.Close();
MessageBox.Show("新增成功!");
}
}
catch (Exception ex)
{
MessageBox.Show("新增错误!请重试!错误信息:" + ex.Message);
return;
}
}
}
private void DeleteFile(string fileName)
{
string filePath = Application.StartupPath + @"\File" + "\\" + fileName;
try
{
if (!File.Exists(filePath))
{
MessageBox.Show("不存在该文件!");
}
else
{
File.Delete(filePath);
MessageBox.Show("删除成功!");
}
}
catch (Exception ex)
{
MessageBox.Show("新增错误!请重试!错误信息:" + ex.Message);
return;
}
}
下载源码:
评论列表: