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

}

相关推荐
MediaTea35 分钟前
Python 第三方库:OpenPyXL(Excel 文件读写与操作)
开发语言·python·excel
点云SLAM39 分钟前
C++ 中dynamic_cast使用详解和实战示例
开发语言·c++·类型转换·dynamic_cast·c++多态·c++继承
CodeByV1 小时前
【C++】C++11:右值引用和移动语义
开发语言·c++
一水鉴天1 小时前
整体设计 全面梳理复盘 之37 元级自动化引擎三体项目(Designer/Master/Transformer)划分确定 + 自用规划工具(增强版)
开发语言·算法·transformer·公共逻辑
自学互联网1 小时前
python爬虫入门案例day05:Pexels
开发语言·爬虫·python
头发还没掉光光1 小时前
C/C++类型转换
c语言·开发语言·c++
馨谙1 小时前
RHEL 存储堆栈完全解析:从硬件到应用的存储管理指南
服务器·开发语言·php
二川bro2 小时前
第38节:WebGL 2.0与Three.js新特性
开发语言·javascript·webgl
MediaTea2 小时前
Python 第三方库:Markdown(将文本渲染为 HTML)
开发语言·前端·python·html
Halo_tjn2 小时前
Java 基于分支和循环结构的专项实验
java·开发语言·计算机