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

}

相关推荐
mudtools3 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下8 小时前
最终的信号类
开发语言·c++·算法
echoarts9 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix9 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz9 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题9 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说10 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔10 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号10 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_10 小时前
QT(4)
开发语言·汇编·c++·qt·算法