c# 读取文本解析

1、filepath是文件路径

public void JXFile(string filepath)

{

//解析文件

string filename = filepath;

m_filename = Path.GetFileNameWithoutExtension(filename);

string newfile = OutTxt(m_filename);

int lastIndex = newfile.LastIndexOf('\\');

if (lastIndex != -1)

{

string result = newfile.Substring(lastIndex + 1);

Console.WriteLine(result); //

}

using (StreamReader reader = new StreamReader(filename))

{

// 跳过第一行

reader.ReadLine();

// 从第二行开始读取

string line;

while ((line = reader.ReadLine()) != null)

{

string[] columns = line.Split(' '); // 假设列是用逗号分隔的

Console.WriteLine(line);

if (!line.Contains("特殊标记 "))

{

foreach (string column in columns)

{

Console.Write($"{column.Trim()} "); // 输出每列的值并去除前后空白

if (!string.IsNullOrEmpty(column))

{

decimal dems = ChangeValue(column.Trim()); //转换函数

File.AppendAllText(newfile, dems.ToString() + " ");

}

}

File.AppendAllText(newfile, "\r");

}

}

}

}

2、调用对应函数

private double ChangeValue(string strvalue)

{

double dData = 0.0f;

if (strData.Contains("E"))

{

dData = double.Parse(strvalue.ToString(), System.Globalization.NumberStyles.Any);

}

else

{

if (!strData.Contains("I")) //对其中特殊符号进行处理比如|

{

dData = double.Parse(strvalue);

}

}

return Math.Round(dData, 5);

}

3、生成新的txt,filename是具体文件名称

private string OutTxt(string filename)

{

string str = string.Empty;

//输出txt

if (!File.Exists(Application.StartupPath + "\\结果\\"+filename+".txt"))

{

FileStream myfs = new FileStream(Application.StartupPath + "\\结果\\" + filename+".txt", FileMode.Create, FileAccess.ReadWrite);

str= Application.StartupPath + "\\结果\\" + filename + ".txt";

myfs.Close();

}

return str;

//是否打开当前txt

Process.Start(Application.StartupPath + "\\结果\\" + filename+".txt");

}

相关推荐
踩着两条虫1 天前
「AI + 低代码」的可视化设计器
开发语言·前端·低代码·设计模式·架构
JoneBB1 天前
ABAP Webservice连接
运维·开发语言·数据库·学习
即使再小的船也能远航1 天前
【Python】安装
开发语言·python
Irissgwe1 天前
类与对象(三)
开发语言·c++·类和对象·友元
雪度娃娃1 天前
转向现代C++——优先选用nullptr而不是0和NULL
开发语言·c++
萌新小码农‍1 天前
python装饰器
开发语言·前端·python
KK溜了溜了1 天前
Python从入门到精通
服务器·开发语言·python
故事和你911 天前
洛谷-【图论2-1】树5
开发语言·数据结构·c++·算法·动态规划·图论
threelab1 天前
Three.js 初中数学函数可视化 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
rockey6271 天前
AScript如何实现LINQ语法
sql·c#·.net·linq·script·eval·expression