获取一个具有多个值的列表框,并将其划分为多个文本文件

本文关键字:划分 文件 文本 一个 获取 列表 | 更新日期: 2023-09-27 18:13:04

我正经历着最艰难的时刻。

我有一个listbox,里面有很多数据。我想要这个listbox,然后有一个按钮来保存它。

按钮将选择存放文件的目录。之后,程序应该开始将这些值保存到命名模式为Seed1.txtSeed2.txt的文本文件中,等等。

问题是,我想在生成的每个文本文件中只放入100个项目,直到列表完成。

保存路径:

        Stream s;
        string folderPath = string.Empty;
        using (FolderBrowserDialog fdb = new FolderBrowserDialog())
        {
            if (fdb.ShowDialog() == DialogResult.OK)
            {
                folderPath = fdb.SelectedPath;
                MessageBox.Show(folderPath);
            }

为了一次保存所有内容,我相信这会起作用:

         int total = list_failed.Items.Count;
           for (int i = 0; i < list_failed.Items.Count; i++)
            {
                StreamWriter text = new StreamWriter(s);
                text.Write(list_failed.Items[i]);
                s.Close();

我不确定剩下的。比如文件名

          string filename;
            int i = 0;
            do
            {
                filename = "Seed" + ++i + ".txt";
            } while (files.Contains(filename));

获取一个具有多个值的列表框,并将其划分为多个文本文件

这是一个可以使用的工作示例。

        string pathname = Server.MapPath("/");
        int counter = 1;
        string file = String.Empty;
        List<string> list = new List<string>();

        //Add the list items
        for (int i = 0; i <= 1234; i++)
        {
            list.Add(String.Format("item {0}", i));
        }

        //write to file
        for (int i = 1; i < list.Count(); i++)
        {
            //generate a dynamic filename with path
            file = String.Format("{0}Seed{1}.txt", pathname, counter);
            //the using statement closes the streamwriter when it completes the process
            using (StreamWriter text = new StreamWriter(file, true))
            {
                //write the line
                text.Write(list[i]);
            }
            //check to see if the max lines have been written
            if (i == counter * 100) counter++;                
        }
    string folderPath;
    const int ITEMS_PER_FILE=100;
    void AskUserForFolder()
    {
        folderPath = string.Empty;
        using (FolderBrowserDialog fdb = new FolderBrowserDialog())
        {
            if (fdb.ShowDialog() == DialogResult.OK)
            {
                folderPath = fdb.SelectedPath;
                // MessageBox.Show(folderPath);
            }
        }
    }
    void SaveItems(ListBox listBox, int seed)
    {
        int total = listBox.Items.Count;
        for ( int fileCount=0;fileCount<listBox.Items.Count/ITEMS_PER_FILE;++fileCount)
        {
            using (StreamWriter sw = new StreamWriter(folderPath + "''" + GetFilePath(folderPath, "filename.txt",ref seed)))
            {
                for (int i = 0; i < listBox.Items.Count; i++)
                {
                    sw.WriteLine(listBox.Items[i+(ITEMS_PER_FILE*fileCount)]);
                }
                sw.Close();
            }
        }
    }
    //I'm not sure about the rest though. Something like this for the filenames perhaps
    /// <summary>
    /// Gets a filename that has not been used before by incrementing a number at the end of the filename
    /// </summary>
    /// <param name="seed">seed is passed in as a referrect value and acts as a starting point to itterate through the list
    /// By passing it in as a reference we can save ourselves from having to itterate unneccssarily for the start each time
    /// </param>
    /// <returns>the path of the file</returns>
    string GetFilePath(string folderpath, string fileName,string extension,ref int seed)
    {
        FileInfo fi = new FileInfo(string.Format("{0}''{1}{2}.{3}", folderPath, fileName, seed,extension));
        while (fi.Exists)
        {
            fi = new FileInfo(string.Format("{0}''{1}{2}.{3}", folderPath, fileName, ++seed,extension));
        }
        return fi.FullName;
    }

尝试遍历ListBox项,并将它们放入最多100项的文件中:

       private void writeItemsToFile(ListBox lb)
        {
        string path = @"c:'test'";
        string filename = "seed";
        int itemCounter = 0;
        int fileCounter = 1;
        StreamWriter sw = new StreamWriter(File.OpenWrite(System.IO.Path.Combine(path,string.Format(filename+"{0}.txt",fileCounter))));
        foreach (var s in lb.Items)
            {
            if (itemCounter > 100)
                {
                fileCounter++;
                itemCounter = 0;
                sw.Flush();
                sw.Close();
                sw.Dispose();
                sw = null;
                sw = new StreamWriter(File.OpenWrite(System.IO.Path.Combine(path,string.Format(filename+"{0}.txt",fileCounter))));
                }
            sw.WriteLine(s.ToString());
            itemCounter++;
            }
        if (sw != null)
            {
            sw.Flush();
            sw.Dispose();
            }
        }