C#在文本文件或csv文件中查找指定字符串
using System.Text.RegularExpressions;
string str = System.IO.File.ReadAllText("c:/k.txt");
Regex reg = new Regex("B");
Match mat = reg.Match(str);
while(mat.Success)
{
MessageBox.Show(mat.Index.ToString());//位置
mat = reg.Match(str, mat.Index+mat.Length);
}
string str = System.IO.File.ReadAllText("~/../../../../1.csv");
Regex reg = new Regex(yemail);
Match mat = reg.Match(str);
if (mat.Success)
{
//Console.WriteLine(mat.Index.ToString());//位置
Console.WriteLine("The supplied address is already in use.");
boolemail = true;
mat = reg.Match(str, mat.Index + mat.Length); //不知道干啥用
}
else
{
//Console.WriteLine("can't find the same emial");
boolemail = false;
break;
}
c#截取两个指定字符串中间的字符串
public static string MidStrEx_New(string sourse, string startstr, string endstr)
{
Regex rg = new Regex("(?<=(" + startstr + "))[.\\s\\S]*?(?=(" + endstr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(sourse).Value;
}//c#截取两个指定字符串中间的字符串
int i = str.IndexOf("\n") + 1; // int j = str.IndexOf("ef");
int j = mat.Index;
string sneed = str.Substring(i, j-i-2);
yname = sneed;
public static string MidStrEx(string sourse, string startstr, string endstr)
{
string result = string.Empty;
int startindex, endindex;
try
{
startindex = sourse.IndexOf(startstr);
if (startindex == -1)
return result;
string tmpstr = sourse.Substring(startindex + startstr.Length);
endindex = tmpstr.IndexOf(endstr);
if (endindex == -1)
return result;
result = tmpstr.Remove(endindex);
}
catch (Exception ex)
{
Log.WriteLog("MidStrEx Err:" + ex.Message);
}
return result;
}
在.csv文件中指定字符串后插入
public static void WriteCsv2(string result)
{
string path = "~/../../../../";//保存路径
string fileName = path + "1.csv";//文件名
string Datedate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//年月日小时分钟秒
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!File.Exists(fileName))
{
StreamWriter sw2 = new StreamWriter(fileName, true, Encoding.UTF8);
sw2.Close();
}
//初始化文件
FileStream fs = new FileStream(@"~/../../../../1.csv", FileMode.Open);
var sw = new StreamWriter(fs);
var sr = new StreamReader(fs);
sw.Flush();
var end = sr.ReadToEnd(); //读取全文
var a = end.IndexOf("Address"); //找到目标位置 应该是邮箱后面的address
fs.Seek(a+1, SeekOrigin.Begin);//在目标位置偏移后写入
sw.WriteLine("\t\n"+result);//换行写入
var zend = end.Substring(a);
sw.Write(zend);//追加偏移后的全文
sw.Close();
}