这对C#来说还很新……我想做的是从上传到内存的.txt文件中解析一堆文本到网页上。
这是.txt文件的样子
.RES B7=121 .RES C12=554 .RES VMAX=4.7μV
Again, it goes on like this for another 50 or so .RES'...I've successfully got it to parse, but not in the desired format...
Here's how I want it to look on the webpage
B7.........121
C12.........554
VMAX.........4.7μV
全部隐藏在id =“ outpt” ...的隐藏面板中,当前设置为visible =“ false”
这是我在C#页面中使用的代码
namespace Sdefault
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpld_Click(object sender, EventArgs e)
{
Stream theStream = file1.PostedFile.InputStream; //uploads .txt file to memory for parse
using (StreamReader sr = new StreamReader(theStream))
{
string tba;
while ((tba = sr.ReadLine()) != null)
{
string[] tmpArray = tba.Split(Convert.ToChar("=")); //Splits ".RES B7=121" to "B7"... but for some reason, It prints it as
//".RES B7.RES C12.RES VMAX"... I would ultimately desire it to be printed as shown above
Response.Write(tmpArray[0].ToString());
var.Text = tba;
outpt.Visible = true;
}
}
}
}
}
我应该朝哪个方向发展?
最佳答案
// Open the file for reading
using (StreamReader reader = new StreamReader((Stream)file1.PostedFile.InputStream))
{
// as long as we have content to read, continue reading
while (reader.Peek() > 0)
{
// split the line by the equal sign. so, e.g. if:
// ReadLine() = .RES B7=121
// then
// parts[0] = ".RES b7";
// parts[1] = "121";
String[] parts = reader.ReadLine().split(new[]{ '=' });
// Make the values a bit more bullet-proof (in cases where the line may
// have not split correctly, or we won't have any content, we default
// to a String.Empty)
// We also Substring the left hand value to "skip past" the ".RES" portion.
// Normally I would hard-code the 5 value, but I used ".RES ".Length to
// outline what we're actually cutting out.
String leftHand = parts.Length > 0 ? parts[0].Substring(".RES ".Length) : String.Empty;
String rightHand = parts.Length > 1 ? parts[1] : String.Empty;
// output will now contain the line you're looking for. Use it as you wish
String output = String.Format("<label>{0}</label><input type=\"text\" value=\"{1}\" />", leftHand, rightHand);
}
// Don't forget to close the stream when you're done.
reader.Close();
}
关于c# - 解析以所需格式C#从.txt文件上传到内存的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7826137/