[英]extracting data from text file using C#
我正在尝试使用C#从文本文件中提取数据,文件的内容如下:
2002/01/10 00:44:51.53 40.4415 -126.0167 25.37 3.92 Md 56 269 147 0.29 NCSN 21208454
现在我希望将文本文件中的数据存储在这样的变量中-
日期= 2002/01/10
时间= 00:44:51.53
lat = 40.4415,依此类推。
这是我使用过的代码片段
public class data
{
public string date, time;
public double lat, lon,depth,mag;
}
class Program
{
static void Main(string[] args)
{
string dt;
List<data> gd = new List<data>();
using (StreamReader sr = new StreamReader("E:\\op.html"))
{
while (sr.Peek() > 0)
{
string str;
string[] arr;
str = sr.ReadLine();
arr = str.Split(' ');
data d = new data();
d.date = arr[0];
//d.time = arr[1];
//d.lat = Convert.ToDouble( arr[2]);
//d.lon = Convert.ToDouble(arr[3]);
//d.depth = Convert.ToDouble(arr[4]);
//d.mag = Convert.ToDouble(arr[5]);
Console.WriteLine(d.date);
//Console.WriteLine(d.time);
//Console.WriteLine(d.lat);
//Console.WriteLine(d.lon);
//Console.WriteLine(d.depth);
//Console.WriteLine(d.mag);
Console.ReadKey();
}
但我只得到d.date的值,无法得到其余的值。 标有“ //”的行将引发错误“ IndexOutOfBound”错误..如何解决此问题?
您需要使用代理的身份验证信息将httpWReq.Proxy.Credentials
设置为NetworkCredentials
。
public class data
{
public string date, time,mag;
public double lat, lon, depth;
}
class Program
{
static void Main(string[] args)
{
string str;
string dt;
List<data> gd = new List<data>();
using (StreamReader sr = new StreamReader("E:\\op.html"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string [] arr = line.Split(new char[] {' '}, System.StringSplitOptions.RemoveEmptyEntries);
while (sr.Peek() > 0)
{
string[] s = new string[] { " " };
char[] c = new char[] { ' ' };
str = sr.ReadLine();
arr = str.Split(c);
data d = new data();
d.date = arr[0];
d.time = arr[1];
d.lon =Convert.ToDouble(arr[3]);
d.depth = Convert.ToDouble (arr[4]);
d.mag = arr[8];
// File.WriteAllText("E:\\abc.txt",d.date);
Console.WriteLine(d.date);
Console.WriteLine(d.time);
//Console.WriteLine(d.lat);
Console.WriteLine(d.lon);
Console.WriteLine(d.depth);
Console.WriteLine(d.mag);
int x = arr[0].Length;
Console.WriteLine(x);
Console.ReadKey();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.