0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ファイルの分割出力

Last updated at Posted at 2022-02-17

読み込んだテキストの内容を別のテキストに出力する。
出力ファイルの上限サイズを設定し、上限サイズを超える場合は別ファイルに分割して出力する。
分割出力する場合はファイル名の末尾に連番を付与する。

            List<string> dataList = new List<string>();

            using (StreamReader sr = new StreamReader(@"C:\Work\test\src.txt", Encoding.GetEncoding("UTF-8"))) {

                while (sr.Peek() >= 0) {

                    dataList.Add(sr.ReadLine());
                }
            }

            var outPath = @"C:\Work\test";
            var outFileBaseName = "out";
            var outFileName = "";

            var dataLen = 0;
            var dataMaxLen = 50000;

            var fileCnt = 0;
            var row = 0;

            var splitFlg = false;

            while (true) {

                splitFlg = false;

                outFileName = outFileBaseName;

                if (fileCnt > 0) {
                    outFileName += "_" + fileCnt.ToString("000");
                }

                using (StreamWriter sw = new StreamWriter(Path.Combine(outPath, outFileName + ".txt"), false, new UTF8Encoding(false))) {

                    dataLen = 0;

                    for (int i = row; i < dataList.Count; i++) {

                        var rowData = dataList[i];
                        dataLen += Encoding.GetEncoding("UTF-8").GetByteCount(rowData);
                        dataLen += 2; // 改行コードの分

                        if (dataLen > dataMaxLen) {
                            fileCnt++;
                            row = i;
                            splitFlg = true;
                            break;
                        }

                        sw.NewLine = "\n";
                        sw.WriteLine(rowData);
                    }

                    if (!splitFlg) {
                        break;
                    }

                }
            }

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?