在文本文件中单列写入数据时出现逻辑错误

本文关键字:错误 数据 文件 文本 单列写 | 更新日期: 2023-09-27 18:05:15

我的用例是通过浏览到包含要引用的数据的文件的位置来从文本文件读取数据。文件中的数据保存在一个列表中。我使用arraylist来获取数据,并循环遍历arraylist并连接每个字符串,然后创建输出文件以将数据存储在单列中,如下所示

Example of a string:    
20050000    
40223120    
40006523

输出示例:

'20050000',    
'40223120',    
'40006523'    
But my code is currently displaying the output in the format:
'20050000'20050000,
'40223120'20050000,
'40006523'40006523    

请帮助。

public List<string> list()
    {
        List<string> Get_Receiptlist = new List<string>();
        String ReceiptNo;
        openFileDialog1.ShowDialog();
        string name_of_Textfile = openFileDialog1.FileName;
        try
        {
            StreamReader sr = new StreamReader(name_of_Textfile);
            {
                while ((ReceiptNo = sr.ReadLine()) != null)
                {
                    Get_Receiptlist.Add(ReceiptNo);
                } // end while
                MessageBox.Show("Record saved in the Data list");// just for testing purpose.
            }// end StreamReader
        }
        catch (Exception err)
        {
            MessageBox.Show("Cannot read data from file");
        }
        return Get_Receiptlist;
    }
    private void button2_Click(object sender, EventArgs e)
    {
        string single_quotation = "'";
        string comma = ",";
        string paths = @"C:'Users'sample'Desktop'FileStream'Output.txt";
        if (!File.Exists(paths))
        {
            // Create a file to write to. 
            using (StreamWriter sw = File.CreateText(paths))
            {
                string[] receipt = list().ToArray();
                foreach (string rec in receipt)
                {
                    string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
                    sw.WriteLine(quoted_receipt);
                    sw.WriteLine(Environment.NewLine);
                }//foreach
                sw.Close();
                MessageBox.Show("Finish processing File");
            }//end using
        }// end if
    }

在文本文件中单列写入数据时出现逻辑错误

在你的方法button2_Click中你有一个坏循环:

string[] receipt = list().ToArray();
foreach (string rec in receipt)
{
  string quoted_receipt = single_quotation + rec + single_quotation + rec + comma;
  sw.WriteLine(quoted_receipt);
  sw.WriteLine(Environment.NewLine);
}//foreach

首先我甚至不确定它是Java…但是如果它是Java,那么我会用下面的代码替换这个片段:

List<String> values = list();
for (int i = 0; i < values.size(); i++)
{
  String rec = values.get(i);
  StringBuilder quoted_receipt = new StringBuilder();
  if (i > 0) 
  {
    // add comma only if the first iteration already passed
    quoted_receipt.append(comma);
  }
  quoted_receipt.append(single_quotation).append(rec).append(single_quotation);
  sw.WriteLine(quoted_receipt.toString());
  sw.WriteLine(Environment.NewLine);
}