这段时间做了一个小监控工具,涉及txt文本的操作,整理总结,防止自己忘记。
零碎知识点:
1、时间转化
class="brush:csharp;gutter:true;"> //时间转换 string xx = "2014/12/19 10:05:10"; DateTime dt = DateTime.ParseExact(xx, "yyyy/MM/dd HH:mm:ss", null);
2、获取本机IP
//获取本地IP IPHostEntry ipentry = Dns.GetHostByName(Dns.GetHostName()); string ip = ipentry.AddressList[0].ToString();
//获取执行路径 //\/:*?"<>| string path = Application.StartupPath+"-"+Application.ProductName;
4、读取文件夹下面的所有文件
DirectoryInfo TheFolder = new DirectoryInfo(txtPath.Text); FileInfo[] dirInfo = TheFolder.GetFiles(); foreach (FileInfo file in dirInfo) { lbox.Items.Add(file.DirectoryName + "\\" + file.Name); }
5、c#程序异常发出报警的声音
//调用系统dll 发出报警声 [DllImport("kernel32.dll")] public static extern bool Beep(int freq, int duration); public void play() { Beep(800, 3000); }
txt文件操作
1、读txt文件
//1次读取所有文本内容
try
{
StreamReader srd = new StreamReader(strpath, Encoding.UTF8);
string result = srd.ReadToEnd();
txtRead.Text = result;
srd.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//循环每行读取 try { StreamReader srd = new StreamReader(strpath, Encoding.UTF8); string str = srd.ReadLine(); while (str != null) { txtRead.Text += str + "\r\n"; str = srd.ReadLine(); } srd.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); }
2、写txt文件
//接着已有内容换行继续写入 try { StreamWriter swt = File.AppendText(strpath); swt.WriteLine(str); swt.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); }
//在文本中写入文本,替换原有内容 try { StreamWriter swt = new StreamWriter(strpath); swt.Write(str); swt.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); }