We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Posted By

pckujawa on 07/25/08


Tagged

file streamReader fileIO fileManipulation appData


Versions (?)


File manipulation, opening, and closing using a streamreader and the system application data folder


Published in: C# 


  1. private string appDataFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
  2. private FileStream defaultFile;
  3. private void openDataFile()
  4. {
  5. string myFolder = appDataFolder + "\\MyFolder";
  6. // check if the default file exists and use its data
  7. try
  8. {
  9. defaultFile = new FileStream(myFolder + "defaults.ini", FileMode.Open);
  10. }
  11. catch (Exception)
  12. {
  13. try
  14. {
  15. Directory.CreateDirectory(myFolder);
  16. defaultFile = new FileStream(myFolder + "defaults.ini", FileMode.Create);
  17. }
  18. catch (System.IO.IOException)
  19. {
  20. //// if not, try to open a file with default data
  21. //OpenFileDialog myDlg = new OpenFileDialog();
  22. //myDlg.Filter = "INI Files (*.INI)|*.INI|All Files (*.*)|*.*||";
  23. //myDlg.InitialDirectory = appDataFolder;
  24. //if (myDlg.ShowDialog() == DialogResult.OK)
  25. //{
  26. // defaultFile = new FileStream(myDlg.FileName, FileMode.Open);
  27. //}
  28. }
  29. }
  30. }
  31. private void readDataFile()
  32. {
  33. try
  34. {
  35. StreamReader sr = new StreamReader(defaultFile);
  36. string lines = sr.ReadLine();
  37. while (!sr.EndOfStream)
  38. {
  39. lines += sr.ReadLine();
  40. }
  41. sr.Close();
  42. }
  43. catch (Exception) { return; }
  44. }
  45. private void saveData()
  46. {
  47. openDataFile();
  48. try
  49. {
  50. StreamWriter sw = new StreamWriter(defaultFile);
  51. sw.WriteLine("text");
  52. sw.Close();
  53. }
  54. catch (Exception) { }
  55. }

Report this snippet 

You need to login to post a comment.