[英]C# loop through files
I am trying to parse.msg files using an MSGReader library and while it works for single files, the moment I try to do it as a loop, nothing works anymore.我正在尝试使用 MSGReader 库解析 .msg 文件,虽然它适用于单个文件,但当我尝试将其作为循环执行时,就再也没有任何效果了。 My code is hideous as I couldn't find a way to grab specific lines from a multiline string, but it works without the loop.我的代码很糟糕,因为我找不到从多行字符串中获取特定行的方法,但它可以在没有循环的情况下工作。
What am I doing wrong here?我在这里做错了什么?
private void btfolder_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK);
foreach (var file in Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath, "*.msg"))
{
using (var msg = new MsgReader.Outlook.Storage.Message(file))
{
var htmlBody = msg.BodyHtml;
tbbody.Text = htmlBody;
string who = tbbody.Lines[42];
string error = tbbody.Lines[46];
who = who.Substring(3, who.Length - 7);
error = error.Substring(0, error.Length - 7);
tbsender.Text = who;
tberror.Text = error;
DataTable dts = new DataTable();
DataTable dt = new DataTable();
dts.Columns.Add("Absender", typeof(string));
dts.Columns.Add("error", typeof(string));
dts.Rows.Add(who, error);
dt.Merge(dts);
dgvemail.DataSource = dt;
}
}
}
I expected the code to cycle through all 9.msg files, update my textboxes and populate my data.table.我希望代码循环遍历所有 9.msg 文件,更新我的文本框并填充我的 data.table。
Instead I get: "startIndex cannot be larger than the length of string. Arg_ParamName_Name"相反,我得到:“startIndex 不能大于字符串的长度。Arg_ParamName_Name”
You can't just assume the length of values, you need to verify that the starting points are correct:您不能只假设值的长度,您需要验证起点是否正确:
//Theres no guarentee you can do any of these:
string who = tbbody.Lines[42];
string error = tbbody.Lines[46];
who = who.Substring(3, who.Length - 7);
error = error.Substring(0, error.Length - 7);
Try validating the message first.首先尝试验证消息。 or atleast cheching the length或者至少检查一下长度
Note: this is ugly and you should figure out a way to valid based on the message format注意:这很丑陋,您应该根据消息格式找出一种有效的方法
if(tbbody.lines.length < 47) {
continue;
}
string who = tbbody.Lines[42];
string error = tbbody.Lines[46];
if(who.length < 11) {
continue;
}
who = who.Substring(3, who.Length - 7);
if(error.length < 8) {
continue;
}
error = error.Substring(0, error.Length - 7);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.