C#分割檔案內容

科睿思博發表於2017-06-28
        static void ReadData(string sourcePath, string targetDirectory)
        {
            FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.Default);
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            string line = string.Empty;
            int seg = 0;

            while (line != null)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < 10000; i++)
                {
                    line = sr.ReadLine();
                    if (line.Trim()=="GO")
                        break;
                    else
                        sb.AppendLine(line);
                }
                seg++;
                string targetPath = targetDirectory + "\\" + Path.GetFileNameWithoutExtension(sourcePath) + "_" + seg.ToString() + Path.GetExtension(sourcePath);
                sb.AppendLine("GO");
                sb.AppendLine();
                WriteData(sb.ToString(), targetPath);
            }
            sr.Close();
            fs.Close();
        }

        static void WriteData(string str, string path)
        {
            FileStream aFile = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter sw = new StreamWriter(aFile);
            sw.Write(str);
            sw.Close();
            aFile.Close();
        }

  

相關文章