using System; using System.IO; using System.Windows.Forms; using System.Collections;namespace CCPress.TTextReader { #region TextReader /// <summary> /// TextReader 的摘要说明。主要用处是封装了读有格式文本文件的功能 /// </summary> public class TextReader { public static int Width = 0;//得到列数 public static int Lenght= 0;//得到行数 private static TextReader _instance = null; public TextReader() {
using System.IO;
using System.Windows.Forms;
using System.Collections;namespace CCPress.TTextReader
{
#region TextReader
/// <summary>
/// TextReader 的摘要说明。主要用处是封装了读有格式文本文件的功能
/// </summary>
public class TextReader
{
public static int Width = 0;//得到列数
public static int Lenght= 0;//得到行数
private static TextReader _instance = null; public TextReader()
{
} //该方法保证产生唯一的实例
public static TextReader Instance()
{
if (_instance == null)
{
_instance = new TextReader();
}
return _instance;
} /// <summary>
/// 读文本文件
/// </summary>
/// <param name="FILE_NAME"></param>
/// <param name="iW"></param>
/// <returns></returns>
public string[,] ReadFile(string FILE_NAME)
{
if ((File.Exists(FILE_NAME)))
{
StreamReader sr = new StreamReader(FILE_NAME,System.Text.Encoding.GetEncoding("GB2312"));
string str = sr.ReadToEnd();
string[,] strTem = FindStringArray(str);
sr.Close();
return strTem;
}
else
{
MessageBox.Show(FILE_NAME + "不存在!","错误报告");
return null;
}
}
/// <summary>
/// 依间隔符号,分解字符串成数组
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string[,] FindStringArray(string str)
{
string[] strLine = str.Split('\r');
int il = strLine.Length;
if(il>0)
{
string[] strTemp = strLine[0].Split(',');
Width = strTemp.Length; //得到列数.
}
else
{
return null;
} Lenght = strLine.Length; //得到行数.
string[,] s = new string[Lenght,Width];
for(int l=0;l<Lenght;l++)
{
for(int w=0;w<Width;w++)
{
s[l,w] = (strLine[l].Split(','))[w];
}
}
return s;
}
public int SetLenght()
{
return Lenght;
}
public int SetWidth()
{
return Width;
}
}
#endregion
}
此例中是依回车符作为分离符,如果不对,请自已改一下。
这是我目前工作中用使用的一个类。试一下吧。
private string[,] getData()
{
int iWidth = 0;
string[,] strTemp = null;
TextReader textReader = TextReader.Instance();
try
{
string FILE_NAME = @"wc_InWarehouseFile_Stub.txt";
strTemp = textReader.ReadFile(FILE_NAME);
int iWidth = textReader.SetWidth();if(iwidth == 2)
return strTemp;
else
return null;
}
catch{}
}
string txtLine;
string[] lineItem;
while(sr.Peek()>=0)
{
txtLine=sr.ReadLine();
lineItem=txtLine.Split(',');
textBox2.Text+=lineItem[0]+","+lineItem[1];
}
sr.Close();