我想问大家一下在C#中怎么读取一个文本文件中的数字呢?譬如那个文本文件中记录了一堆数字……我是一个新手,还没有入门,谢谢大家!假设文本文件data.txt记录了下面读数据:
100 150
125 175
150 200
150 225
150 250
150 325
200 250
250 300
100 150
125 175
150 200
150 225
150 250
150 325
200 250
250 300
解决方案 »
- 未处理 System.ExecutionEngineException 异常
- 软件升级的问题?希望高手可以帮我解答.先谢过
- 求助,这简单算法错在哪里?
- 请问datagridview里面的datagridviewcheckboxcolumn列里面的checkbox后面可以跟文字吗?
- C#项目的问题
- 关于数据查询和返回的问题
- 在什么地方可以找到不限制流量的主机?
- 为什么我的.net装上之后,不能创建C#的asp.net project?
- 如何把String转换成INT的问题
- 向高手求助,如何不擦除父控件背景条件下,让子控件显示正常?
- 怎样备份和还原SQL SERVER数据库
- 如何在C#中向系统发送一个等待的消息?
//textPath文件路径
string line = reader.ReadLine();
//line 是读取一行,下面就自己处理了
/// 读文件到字符串中
/// </summary>
/// <param name="sFileName">文件名</param>
/// <returns></returns>
public string FromFile(string sFileName)
{
string content = "";
FileStream fs = File.Open(sFileName, FileMode.Open, FileAccess.Read);
StreamReader r = new StreamReader(fs);
content = r.ReadToEnd();
r.Close();
fs.Close();
return content;
} /// <summary>
/// 把字符串写入文件(会覆盖同名文件)
/// </summary>
/// <param name="fname"></param>
/// <param name="text"></param>
/// <returns></returns>
public bool ToFile(string fname, string text)
{
FileStream fs = File.Open(fname, FileMode.Create, FileAccess.ReadWrite);
StreamWriter w = new StreamWriter(fs);
w.Write(text);
w.Close();
fs.Close();
return true;
}
string[] s2 = s.Splite(" ");
则s2[0]="100" s2[1]="150"
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;public class MyClass
{
public static void Main()
{
string path = "C:\\1.txt";//文件所在路径
StreamReader sr = new StreamReader(path, Encoding.Default);
List<string> tempList = new List<string>();
string temp;
while((temp = sr.ReadLine()) != null)//如果不是空
{
tempList.Add(temp.Trim());//除去前后空格,放入List
}
sr.Close();
int count = tempList.Count;//
int[,] array = new int[count, 2];
int index = 0;
Regex regex = new Regex("\\s+");//分割用正则表达式
string[] tempArray;
foreach(string s in tempList)
{
tempArray = regex.Split(s);
if(tempArray == null || tempArray.Length != 2)//为空或长度不是2
{
continue;
}
array[index, 0] = Convert.ToInt32(tempArray[0]);
array[index, 1] = Convert.ToInt32(tempArray[1]);
++index;
}
for(int i = 0; i < count; ++i)
{
Console.WriteLine("tempArray[0]={0},tempArray[1]={1}",array[i, 0],array[i, 1]);
}
Console.ReadLine();
}
}