如何从文件中提取特定数据?

时间:2012-04-19 17:10:47

标签: c#

我有一个包含温度数据的文件。我需要从中提取温度并将结果保存在新文件中只有温度。

这是文件的内容:

BCAST:000D6F00017620E9, 02=34.23
BCAST:000D6F00017620E9, 02=12.3
BCAST:000D6F00017620E9, 02=54.01
BCAST:000D6F00017620E9, 02=12.34
BCAST:000D6F00017620E9, 02=16.22

需要在每次=即34.23,12.3,54.01等之后提取数据

我尝试过使用子字符串,但是当我将文件作为字符串读取时它可以使用,它只是生成第一行的子字符串,其余部分保持不变。以下是我的代码。请提示!

string temp2 = System.IO.File.ReadAllText(@"C:********\temperature.txt");
int c = temp2.IndexOf("=");
string temp3 = temp2.Substring(c + 1);
System.IO.File.WriteAllText(@"C:\*******\temperature2.txt",temp3);

此代码的输出为:

34.23
BCAST:000D6F00017620E9, 02=12
BCAST:000D6F00017620E9, 02=54
BCAST:000D6F00017620E9, 02=12
BCAST:000D6F00017620E9, 02=16

4 个答案:

答案 0 :(得分:6)

ReadAllText将整个文件作为一个字符串返回。循环一行数组并在每一行上使用子字符串代码会更有意义。

编辑 ReadAllLines是静态调用:

string[] lines = System.IO.File.ReadAllLines(fileName);

或者,使用流一次读取一行:

var sr = new StreamReader(fileStream);
while (!sr.EndOfStream)
{
  var line = sr.ReadLine();
  // .. per line sub string
}

编辑2 我制定了一个完整的解决方案(注意我更喜欢流读取而不是读取所有样式 - 它对于非常大的文件更有效 - 所以习惯于这是一个很好的做法)

var sb = new StringBuilder();

using (var file = new FileStream("C:/tmp/temps.txt", FileMode.Open, FileAccess.Read))
{
  var sr = new StreamReader(file);

  while (!sr.EndOfStream)
  {
    var nextLine = sr.ReadLine();
    int indexOfEqualSign = nextLine.IndexOf("=");

    if (indexOfEqualSign == -1 || indexOfEqualSign == nextLine.Length)
      continue;

    string rightHandSide = nextLine.Substring(indexOfEqualSign + 1);
    sb.AppendLine(rightHandSide);
  }
}

File.WriteAllText("C:/tmp/temps2.txt", sb.ToString());

答案 1 :(得分:1)

你是在正确的轨道上,但是你需要遍历文件中的行,然后在=:

上进行拆分
string[] lines = File.ReadAllLines(@"C:\********\temperature.txt"); 
StringBuilder temperatures = new StringBuilder();

foreach (string line in lines)
{
    string[] parts = line.Split('=');

    if (lines.Length > 1)
    {
        tempatures.Append(lines[1]));
        tempatures.Append("\n");
    }
}

File.WriteAllText(@"C:\*******\temperature2.txt", tempatures.ToString());

答案 2 :(得分:1)

一次读取每一行,在等号上分开。 请务必包含:StreamReader的System.IO

try
{
    // Create an instance of StreamReader to read from a file.
    // The using statement also closes the StreamReader.
    using (StreamReader sr = new StreamReader(@"C:********\temperature.txt"))
    {
        String line;
        // Read and display lines from the file until the end of
        // the file is reached.
        while ((line = sr.ReadLine()) != null)
        {
            try
            {
                Console.WriteLine(line.Split('=')[1]);
            } 
            catch
            {
                Console.WriteLine("Contained No equals sign: " + line);
            }
        }
    }
}
catch (Exception e)
{
    // Let the user know what went wrong.
    Console.WriteLine("The file could not be read:");
    Console.WriteLine(e.Message);
}

来源:http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx

答案 3 :(得分:0)

string readFile =  @"C:\****\temperature.txt");
string writeFile = @"C:\****\temperature2.txt");
List<string> lines = new List<string>lines;
....
string sr = new StreamReader(readFile);
foreach (string line in sr.ReadAllLines())
{
   int c = line.IndexOf("=");
   if ( c >= 0 ) {
      lines.Add(line.SubString(c+1);
   }
}

if ( lines.Count > 0 ) {
  System.IO.File.WriteAllText(writeFile, 
     string.Join(Environment.NewLine, lines.ToArray*());
}