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");

}

相关推荐
nvvas2 分钟前
Java 入门(四):数组——数据的集合管理
java·开发语言
Y3815326621 小时前
SERP 数据清洗实战:字段标准化、日期解析与去重键
开发语言·数据库·python·python数据库
君顾11 小时前
本地城市低空经济管理系统定制:城市级低空运营平台架构与落地实战
java·开发语言·飞手
多多鼠2 小时前
System Prompt 的“版本漂移”问题:从变更管理到 A/B 测试体系
开发语言·网络·人工智能·python·langchain
WiChP2 小时前
【V0.1B16】从零开始的2D游戏引擎开发之路
开发语言·算法·游戏引擎
孙启超3 小时前
【AI开发之Rust】第 8 课:泛型、trait 与 trait 对象
开发语言·后端·rust
2501_933670793 小时前
经营财务岗技能栈拆解:Excel、SQL、BI、预算分析怎么准备
开发语言
数据狐(Datafox)4 小时前
1688商品列表API接口解析(附 JSON 样例)
java·开发语言·数据库·爬虫·json
专注仿真4 小时前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类
小灰灰搞电子4 小时前
Rust Once 、OnceLock、LazyLock 一次性初始化详解
开发语言·后端·rust