您的位置:首页 > 编程语言 > C#

C#字符串相关操作和文件操作

2013-11-28 16:43 190 查看
//打开单个文件
private void fileBtOpen_Click(object sender, EventArgs e)
{

/*
*打开格式为html文件
*/
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "选择文件";
fileDialog.Filter = "html files(*.html)|*.html";
fileDialog.FilterIndex = 1;
fileDialog.RestoreDirectory = true;
/*
*文件的读写操作
*/

if (fileDialog.ShowDialog() == DialogResult.OK)
{
Button btn = (Button)sender;
btn.Enabled = false;

//将数据写入一个文件
string filePathName = "e:\\Errorfile.txt";
fileName.Text = fileDialog.FileName;

//读写操作流
StreamReader sr = new StreamReader(fileDialog.FileName, Encoding.Default);
StreamWriter sw = new StreamWriter(filePathName, true, Encoding.Default);

//一行一行读文件
string strLine = sr.ReadLine();

string strheadValue = "";
string strbodyValue = "";

//打印html标题
string strhtmlPathName = fileName.Text;
int nhtmlBegin = strhtmlPathName.LastIndexOf("\\");
int nhtmlEnd = strhtmlPathName.LastIndexOf("l");
string strhtmlName = strhtmlPathName.Substring(nhtmlBegin + 1, nhtmlEnd - nhtmlBegin - 1);
sw.WriteLine("文件名:" + strhtmlName + "l");

bool bhead = false;
bool bbody = false;
//读文件
while (strLine != null)
{
//bool body = false;

//打印货号

if (strLine.Contains("货号:"))
{
int nstrGoodsBegin = strLine.IndexOf("货号:");
int nstrGoodsEnd = strLine.LastIndexOf("</DIV>");
strheadValue = strLine.Substring(nstrGoodsBegin + 4, nstrGoodsEnd - nstrGoodsBegin - 5);
//sw.WriteLine("head=" + headName);
bhead = true;

}

//打印value值

if (bhead == true)
{
if (strLine.Contains(":tsc"))
{
string body;
int nbodyFirst;
int nbodyLast;

{
//切割字符
string[] strSpilt = strLine.Split(' ');
for (int i = 0; i < strSpilt.Length; i++)
{
body = strSpilt[i].Trim();
if (body.Contains("value="))
{
//截取字符
nbodyFirst = body.IndexOf("=");
nbodyLast = strSpilt[i].Length;
//截取字符
strbodyValue = body.Substring(nbodyFirst + 1, nbodyLast - nbodyFirst - 1);
if (!string.IsNullOrEmpty(strbodyValue))
{
string Cbody1 = strbodyValue.Substring(0, strbodyValue.LastIndexOf("-"));
string Ustr = Cbody1.ToUpper();

if (strheadValue.Equals(Ustr))
{
sw.WriteLine("head=" + strheadValue);
sw.WriteLine("body=" + strbodyValue);
sw.WriteLine("OK");

}
else
{
sw.WriteLine("head=" + strheadValue);
sw.WriteLine("body=" + strbodyValue);
sw.WriteLine("NG");

}

}

}
}
}
bhead = false;
bbody = true;

}
}

//读取下一行
strLine = sr.ReadLine();
}
//关闭文件流
sr.Close();
sw.Close();
}
MessageBox.Show("文件检查完毕,检查结果文件存放在e:\\Errorfile.txt");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: