将每 100 行的平面文件目标拆分为一个新文件

Split flat file destination for every 100 rows into a new file

我目前有一个数据流任务,它有一个 OLEDB 源和一个平面文件目标。

我现在必须修改它以像现在一样创建一个平面文件,但每 100 行创建一个新文件。

所以如果总共有 250 行,我将不得不创建 3 个文件。

file1.txt  // contains rows 1-100
file2.txt  // 101-200
file3.txt  // 201-250

行数是动态的,我事先不知道要创建多少rows/files。

我有什么选择?

我正在为这个项目使用 VS 2008。

我在脚本任务中做了类似的事情:

    public void Main()
    {
        string var_FileSource = Dts.Variables["var_FileSource"].Value.ToString();
        string baseName = var_FileSource + "file_";

        StreamWriter writer = null;

        try
        {
            using (StreamReader inputfile = new System.IO.StreamReader(var_FileSource + "P:\txt"))  
            {

                int count = 0;
                int filecount = 0;
                string line;

                while ((line = inputfile.ReadLine()) != null)
                {

                    if (writer == null || count > 99)
                    {
                        count = 0;
                        if (writer != null)
                        {
                            writer.Close();
                            writer = null;
                        }
                        ++filecount;
                        writer = new System.IO.StreamWriter(baseName + filecount.ToString() + ".txt", true);
                    }
                    writer.WriteLine(line);

                    ++count;
                }
            }
        }
        catch (Exception ex)
        {
            Dts.TaskResult = (int)ScriptResults.Failure;
        }

        finally
        {
            if (writer != null)
                writer.Close();
        }

        Dts.TaskResult = (int)ScriptResults.Success;
    }

此脚本应将目标文件分成 100 行子文件,类似于您想要的。我相信 C# 专家可以提出一些改进建议。

编辑:同时更改变量引用的所有路径,以及拆分文件的计数值。这将使以后的更改变得更加容易。