日期:2014-05-18  浏览次数:20629 次

一个用filestream操作文本文件的问题
想做一个生成一组7位随机数的东东
思路是用filestream类,将生成的一组7位数导入到一个叫MyTest.txt的文本文件中,具体见以下代码:
 private void button1_Click(object sender, EventArgs e)
  {
  OutputToNotepad();
  }

 /// <summary>
  /// 将需要的内容输入到指定的记事本中
  /// </summary>
  private void OutputToNotepad()
  {
  string path = @"c:\temp\MyTest.txt";

  // Delete the file if it exists.
  if (File.Exists(path))
  {
  File.Delete(path);
  }

  //Create the file.
  using (FileStream fs = File.Create(path))
  {
  AddText(fs, "这是一个七位数的序列:");
   
  AddText(fs, "\r\n\r\n\r\n");

  for (int i = 1; i <= 5; i++)
  {
  AddText(fs, GetRandomData().ToString() + " ");
  //Split the output at every 10th character.
  if (Math.IEEERemainder(Convert.ToDouble(i), 5) == 0)
  {
  AddText(fs, "\r\n");
  }
  }
   
  }  
  }
  private static void AddText(FileStream fs, string value)
  {
  byte[] info = new UTF8Encoding(true).GetBytes(value);
  fs.Write(info, 0, info.Length);
  }

  /// <summary>
  /// 得到一个七位数的随机数
  /// </summary>
  private string GetRandomData()
  {
  Random randObj = new Random();
  string str = "";
  for (int j = 0; j < 7; j++)
  {
  str = str + randObj.Next(10);
  }  
  return str;  
  }

想要的结果应该是这样:
这是一个七位数的序列:
8681889 1837393 1406292 8303686 5157394

结果出来的是这样的现象:
这是一个七位数的序列:
4772963 4772963 4772963 4772963 4772963 

写得很繁琐,不知有没表达清,请各位大大指点。


------解决方案--------------------
把 Random randObj = new Random(); 声明为全局变量