在一列中的文本文件中写入数据时的逻辑错误

时间:2013-03-22 16:35:28

标签: c# filestream

我的用例是通过浏览到包含要引用的数据的文件的位置来读取文本文件中的数据。文件中的数据保存在列表中。我使用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
    }

1 个答案:

答案 0 :(得分:1)

在你的方法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);
}