急 C# 怎么将一个txt文件按标记行拆分生成多个txt文件

.Net技术 码拜 8年前 (2016-05-15) 1402次浏览
如图,本人有一个文件1.txt
想根据行标识#a#,#b#,#c#等(有很多行,数量不定,但 都是此规律)拆分成单个以#号中中间字符命名的txt文件存放到磁盘下。效果如下所示:
急 C# 怎么将一个txt文件按标记行拆分生成多个txt文件
解决方案

10

class Program
  {
    static void Main(string[] args)
    {
      var lines = File.ReadAllLines("c:\source.txt");
      var processedLines = new List<string>();
      var name = string.Empty;
      foreach (var line in lines)
      {
        if(IsStartLine(line))
        {
          if(processedLines.Count > 0)
          {
            File.WriteAllLines(name, processedLines);
            processedLines.Clear();
          }
          name = GetFileName(line);          
        }
        else
        {
          processedLines.Add(line);
        }
      }
      if (processedLines.Count > 0)
      {
        File.WriteAllLines(name, processedLines);
        processedLines.Clear();
      }
    }
    public static bool IsStartLine(string l)
    {
      return l.StartsWith("#") && l.EndsWith("#");
    }
    public static string GetFileName(string l)
    {
      return l.Substring(1, l.Length - 2);
    }
  }

怎么感谢本人。

5

引用:
class Program
  {
    static void Main(string[] args)
    {
      var lines = File.ReadAllLines("c:\source.txt");
      var processedLines = new List<string>();
      var name = string.Empty;
      foreach (var line in lines)
      {
        if(IsStartLine(line))
        {
          if(processedLines.Count > 0)
          {
            File.WriteAllLines(name, processedLines);
            processedLines.Clear();
          }
          name = GetFileName(line);          
        }
        else
        {
          processedLines.Add(line);
        }
      }
      if (processedLines.Count > 0)
      {
        File.WriteAllLines(name, processedLines);
        processedLines.Clear();
      }
    }
    public static bool IsStartLine(string l)
    {
      return l.StartsWith("#") && l.EndsWith("#");
    }
    public static string GetFileName(string l)
    {
      return l.Substring(1, l.Length - 2);
    }
  }

怎么感谢本人。

晚了一步。 楼上的方案比本人的好。用他的吧。

5

 if (str.Length == 3 && str[0] == "#" && str[2] == "#")
                    {
                        fileCount++;
                        file = @"C:\testDir" + str[1] + ".txt";
if(sw!=null)
{
sw.Flush();sw.Close();sw.Dispose();
}
                        sw = new StreamWriter(file, false);
                    }

加上这段

50

/// <summary>
        /// 拆分txt
        /// </summary>
        /// <param name="fileName">原始文件路径</param>
        /// <returns>拆分文件数</returns>
        public static int SplitTxt(string fileName)
        {
            using (StreamReader sr = new StreamReader(fileName))
            {
                int fileCount = 0;//文件数
                string str = string.Empty;//原始文件每行数据
                string file = string.Empty;//拆分文件名
                StreamWriter sw = null;
                while ((str = sr.ReadLine()) != null)
                {
                    if (str.Length == 3 && str[0] == "#" && str[2] == "#")
                    {
                        fileCount++;
                        file = @"C:\testDir" + str[1] + ".txt";
                        if (sw != null)
                        {
                            sw.Close();
                        }
                        
                        sw = new StreamWriter(file, false);
                        continue;
                    }
                    //写入文件
                    if (sw != null && File.Exists(file))
                        sw.WriteLine(str);
                }
                if (sw != null)
                {
                    sw.Flush();
                    sw.Close();
                    sw.Dispose();
                }
                return fileCount;
            }
        }

已测试通过,你可以本人在优化一下。

5

foreach(Match m in Regex.Matches(File.ReadAllText(YOURFILENAME), @"#(\w+)#\r\n([^#]+)"))
	File.WriteAllText(m.Groups[1].Value + ".txt", m.Groups[2].Value);

5

引用:
foreach(Match m in Regex.Matches(File.ReadAllText(YOURFILENAME), @"#(\w+)#\r\n([^#]+)"))
	File.WriteAllText(m.Groups[1].Value + ".txt", m.Groups[2].Value);

假如换行符不是\r\n,第一行里本人替换下
假如有输出路径,加到第二行m.Groups[1].Value + “.txt”的前面

15

ASHX版的,把路径一段改下就可以了

    string filename = "";
    StringBuilder builder = new StringBuilder();
    string path = "";
    public void ProcessRequest(HttpContext context)
    {
        path = context.Server.MapPath(".");
        string[] lines = File.ReadAllLines(context.Server.MapPath("1.txt"));
        foreach (string line in lines)
        {
            if (line.StartsWith("#"))
            {
                writeFile();
                filename = line.Substring(1, 1) + ".txt";
            }
            else
            {
                builder.AppendLine(line);
            }
        }
        writeFile();
    }
    void writeFile()
    {
        string content = builder.ToString();
        if (content != "")
        {
            File.WriteAllText(path + "\" + filename, content);
        }
        builder.Clear();
    }

急 C# 怎么将一个txt文件按标记行拆分生成多个txt文件

5

一事一议比较好

        static void Main(string[] args)
        {
            string name = "";
            char[] fmt = { "#" };
            foreach (var r in fileGet("1.txt"))
            {
                var buf = r.Trim(fmt);
                if (buf != r) name = buf + ".txt";
                else filePut(name, buf);
            }
        }
        static IEnumerable<string> fileGet(string fileName)
        {
            using (StreamReader sr = new StreamReader(fileName))
            {                
                string buf;
                while ((buf = sr.ReadLine()) != null) yield return buf;
            }
        }
        static void filePut(string fileNmae, string content)
        {
            using (var sw = new StreamWriter(fileNmae, true))
            {
                sw.WriteLine(content);
            }
        }

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明急 C# 怎么将一个txt文件按标记行拆分生成多个txt文件
喜欢 (0)
[1034331897@qq.com]
分享 (0)