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

}

相关推荐
weixin_472339463 分钟前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
枯萎穿心攻击37 分钟前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue2 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
m0_555762903 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
浪裡遊4 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
lzb_kkk4 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼5 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
简佐义的博客5 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang
程序员爱钓鱼5 小时前
【无标题】Go语言中的反射机制 — 元编程技巧与注意事项
开发语言·qt