一:文件操作
1:判断文件是否存在
if (File.Exists("文件名称"))
{
//存在
}
else
{
//不存在
}
2:创建文件
FileStream fs = new FileStream("文件名称", FileMode.Create);
3:打开已存在文件
FileStream fs = File.Open("文件名称", FileMode.Open);
4:文件写入流
StreamWriter sw = new StreamWriter(fs);
5:文件读取流
StreamReader sr = new StreamReader("ipconfig.ini");
6:清空文件内容
fs.SetLength(0);
7:写入文件内容
sw.Write("写入的数据内容");
8:读取文件全部内容
string data = sr.ReadToEnd();
9:清空缓冲区
sw.Flush();
10:关闭流
sw.Close();
fs.Close();
二:字符串操作
1:获取字符串中指定字符的位置
字符串..IndexOf("指定字符");
2:截取字符串两个位置之间的字符串
得到的字符串=data.Substring(开始位置, 结束位置);
3:用正则表达式获取开始和结束字符串中间的值
/// <summary>
/// 获得字符串中开始和结束字符串中间得值
/// </summary>
/// <param name="str">字符串</param>
/// <param name="s">开始</param>
/// <param name="e">结束</param>
/// <returns></returns>
public static string GetValue(string str, string s, string e)
{
Regex rg = new Regex("(?<=(" + s + "))[.\\s\\S]*?(?=(" + e + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(str).Value;
}
三:代码应用展示
public partial class SystemSet : Page
{
public SystemSet()
{
InitializeComponent();
}
///加载界面调用
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (File.Exists("ipconfig.ini"))//如果存在文件就加载文件内容
{
int posS, posE;
string data,s1;
StreamReader sr = new StreamReader("ipconfig.ini");
//读取文件全部内容
data = sr.ReadToEnd();
//获取本地IP:后处在字符串的位置
posS = data.IndexOf(":")+1;
//获取结束位置
posE = data.IndexOf("\r\n");
//提取显示本地IP
s1 = data.Substring(posS, posE - posS);
textLocalIP.Text = s1;
//去除本地IP后的内容
data = data.Substring(posE+2);
//本地端口
posS = data.IndexOf(":") + 1;
posE = data.IndexOf("\r\n");
s1 = data.Substring(posS, posE - posS);
textLocalPort.Text = s1;
data = data.Substring(posE + 2);
//目的IP
posS = data.IndexOf(":") + 1;
posE = data.IndexOf("\r\n");
s1 = data.Substring(posS, posE - posS);
textPurpostIP.Text = s1;
data = data.Substring(posE + 2);
//目的端口
posS = data.IndexOf(":") + 1;
posE = data.IndexOf("\r\n");
s1 = data.Substring(posS, posE - posS);
textPurpostPort.Text = s1;
sr.Close();
}
}
/// IP保存
private void IPSave_Click(object sender, RoutedEventArgs e)
{
if (File.Exists("ipconfig.ini"))
{
//存在文件
FileStream fs = File.Open("ipconfig.ini", FileMode.Open);
StreamWriter sw = new StreamWriter(fs);
//先清空文件内容
fs.SetLength(0);
//开始写入
sw.Write("LocalIP:" + textLocalIP.Text + "\r\n");
sw.Write("LocalPort:" + textLocalPort.Text + "\r\n");
sw.Write("PurpostIP:" + textPurpostIP.Text + "\r\n");
sw.Write("PurpostPort:" + textPurpostPort.Text + "\r\n");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
else
{
FileStream fs = new FileStream("ipconfig.ini", FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.Write("LocalIP:"+ textLocalIP.Text+"\r\n");
sw.Write("LocalPort:" + textLocalPort.Text + "\r\n");
sw.Write("PurpostIP:" + textPurpostIP.Text + "\r\n");
sw.Write("PurpostPort:" + textPurpostPort.Text + "\r\n");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
MessageBox.Show("IP参数保存成功!", "提示");
}
}