如何将所有文本文件数据写入excel.csv C#控制台 [英] How to write all text files data into excel.csv C# console

查看:89
本文介绍了如何将所有文本文件数据写入excel.csv C#控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

static void Main(string[] args)
        {
            string readFile = @"C:\Log\*.txt";
            string writeFile = @"D:\DataLocate_PR_id.csv";
            Creating_CSV_File(readFile, writeFile);
        }

        private static void Creating_CSV_File(string readFrom, string writeTo)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                using (StreamReader sr = new StreamReader(readFrom))
                {
                    string delimiter = ";";
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] columns = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        sb.AppendLine(string.Join(delimiter, columns));
                    }
                }
                File.WriteAllText(writeTo, sb.ToString());
            }
            catch(Exception ex)
                {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                }
            }





我的尝试:



当前代码获取错误(路径中的字符非法),这是因为我给*读取所有.txt,但它只需要特定的.txt文件,但是我想让它全部读取.txt文件。



What I have tried:

Current code getting error(Illegal characters in path), this is because I give * to read all .txt, but its need specific .txt file only, but I want it to read all .txt files.

推荐答案

如果你想读取所有.txt文件,然后使用Directory类对象单独读取它,然后逐个读取文件

见尾随代码

if you want to read all .txt file, then read it separately using Directory class object and then read file one by one
see trailing code
string[] array2 = Directory.GetFiles(@"C:\", "*.txt");

	// get all files and read them one by one.
	foreach (string name in array1)
	{
	    //your 'Creating_CSV_File' function goes here
	}


阅读以下内容:

http ://www.dotnetperls.com/main [ ^ ]

http://www.dotnetperls.com/directory-getfiles [ ^ ]
Read these :
http://www.dotnetperls.com/main[^]
http://www.dotnetperls.com/directory-getfiles[^]


这篇关于如何将所有文本文件数据写入excel.csv C#控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆