今天开始写WinForm,这次主要实现两个常用的基本功能:
通过不同的方式获取程序运行路径
通过不同的方式读写文本文件
c#对于这两个功能,实现方式还是比较多的,下面会以不同的方式去实现。
开发工具:Visual Studio 2013
.NET Framework版本:4.5
具体实现代码如下:
-
获取程序运行路径的方式
//获得当前执行的exe的文件名
//如果是调试模式,会输出*.vshost.exe
//输出:E:\c#小记\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\WindowsFormsApplication1.vshost.exe
string path = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
//取和设置当前目录的完全限定路径。
//输出:E:\c#小记\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug
path = Environment.CurrentDirectory;
//获取应用程序的当前工作目录。
//输出:E:\c#小记\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug
path = System.IO.Directory.GetCurrentDirectory();
// 获取基目录,它由程序集冲突解决程序用来探测程序集。
//输出:E:\c#小记\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\
path = AppDomain.CurrentDomain.BaseDirectory;
获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。
//输出:E:\c#小记\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug
path = Application.StartupPath;
///获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。
//输出:E:\c#小记/WindowsFormsApplication1/WindowsFormsApplication1/bin/Debug/WindowsFormsApplication1.EXE
path = Application.ExecutablePath;
///获取或设置包含该应用程序的目录的名称。
//输出:E:\c#小记\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\
path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
-
读写文本文件的方式
/*直接操作文本,这种方式最简单*/
//读取所有内容
string text = System.IO.File.ReadAllText("d:\\1.txt");
//读取所有行
List<string> listText = System.IO.File.ReadLines("d:\\1.txt").ToList();
//写入内容
System.IO.File.WriteAllText("d:\\1.txt", "要写入的内容");
//分行写入
List<string> list = new List<string>{
"第一行内容",
"第二行内容"
};
System.IO.File.WriteAllLines("d:\\1.txt", list);
//追加内容
System.IO.File.AppendAllText("d:\\1.txt", "要追加的内容");
//追加行
System.IO.File.AppendAllLines("d:\\1.txt", list);
/*流读取*/
System.IO.FileStream fs = new System.IO.FileStream("d:\\1.txt", System.IO.FileMode.OpenOrCreate);
System.IO.StreamReader sr = new System.IO.StreamReader(fs);
//按行读取数据
string tempText = "";
while ((tempText = sr.ReadLine()) != null)
{
text += tempText;
}
//读取所有内容
//text = sr.ReadToEnd();
//释放流
sr.Close(); fs.Close();
/*流写入*/
fs = new System.IO.FileStream("d:\\1.txt", System.IO.FileMode.OpenOrCreate);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
//写入一行数据
sw.WriteLine("第一行内容");
//写入数据
sw.Write("要写入的内容");
//输出缓冲区内的数据
sw.Flush();
//释放流
sw.Close(); fs.Close();
由简入繁,拿来即用
欢迎关注公众号: dotnet编程大全
技术群: 需要进技术群的添加小编微信mm1552923,备注:加群;