Tuesday, 31 July 2012

save file without using save file dialog


  1. private void Save_Click(object sender, EventArgs e)
  2.     {
  3.  
  4.         string filePath = txtFilePath.Text;
  5.  
  6.         if (!File.Exists(filePath))
  7.         {
  8.             FileStream fs = File.Create(filePath);
  9.             fs.Close();
  10.         }
  11.  
  12.         using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
  13.         {
  14.             using (StreamWriter sw = new StreamWriter(fs))
  15.             {
  16.                 foreach (string line in employeeList.Items)
  17.                 {
  18.                     sw.WriteLine(line);
  19.                 }
  20.             }
  21.         }
  22.             }
  23.        
  24. string path = txtFilePath.Text;
  25.  
  26. // This text is added only once to the file.
  27. if (!File.Exists(path))
  28. {
  29.     using (StreamWriter sw = File.CreateText(path))
  30.     {
  31.         foreach (var line in employeeList.Items)
  32.             sw.WriteLine(line.ToString());
  33.     }  
  34. }
  35. else
  36. {
  37.     using (StreamWriter sw = File.AppendText(path))
  38.     {
  39.         foreach (var line in employeeList.Items)
  40.             sw.WriteLine(line.ToString());
  41.     }
  42. }
  43.        
  44. public void Save_Click(object sender, EventArgs e)
  45. {
  46.     StreamWriter file =
  47.       new StreamWriter(txtFilePath.Text, true);//Open and append
  48.     foreach (object item in employeeList.Items) {
  49.        file.WriteLine(item.toString());
  50.     }
  51.     file.Close();
  52. }

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Popular Posts