Skip to main content

Beginners Guide to File Handling in C#, .net


Make a new project in Visual Studio (Console App)
Add a new .cs file named as MySetting.cs, in that file copy paste the following code


1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

namespace file_handling

{

 class MySettings

 {

  public int MyNumber {
   get;
   set;
  }

  public string MyData {
   get;
   set;
  }

  public void Save()

  {

   Stream stream = File.Create(SettingsFile);

   StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);

   writer.WriteLine(MyNumber);

   writer.WriteLine(MyData);

   writer.Close();

   stream.Close();

  }

  public static MySettings Load()

  {

   if (!File.Exists(SettingsFile))

   return DefaultSetting;

   Stream stream = File.OpenRead(SettingsFile);

   StreamReader reader = new StreamReader(stream, Encoding.UTF8);

   string firstline = reader.ReadLine();

   string secondline = reader.ReadLine();

   reader.Close();

   return new MySettings

   {

    MyNumber = int.Parse(firstline),

    MyData = secondline

   };

  }

  private static string SettingsFolder

  {

   get

   {

    string folder = "C:\\File Handling";

    folder = Path.Combine(folder, "my company");

    folder = Path.Combine(folder, "my app");

    if (!Directory.Exists(folder))

    Directory.CreateDirectory(folder);

    return folder;

   }

  }

  private static string SettingsFile

  {

   get

   {

    return Path.Combine(SettingsFolder, "Settings.txt");

   }

  }

  private static MySettings DefaultSetting

  {

   get

   {

    return new MySettings

    {

     MyNumber = 0,

     MyData = " Harshit Rastogi ",

    };

   }

  }

 }

}

//In the program.cs file add the following code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

namespace file_handling

{

 class Program

 {

  static void Main(string[] args)

  {

   Console.WriteLine("Loading settings");

   MySettings settings = MySettings.Load();

   Console.WriteLine("My Number ={0}", settings.MyNumber);

   Console.WriteLine("My data ={0}", settings.MyData);

   Console.WriteLine();

   Console.WriteLine("upadating settings and printing at next run");

   settings.MyNumber++;

   settings.MyData += "\n " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " " + DateTime.Now.Millisecond.ToString() + " ms ";

   settings.Save();

   Console.WriteLine("done");

   Console.ReadLine();

  }

 }

}




Yes you are done with file handling reading and writing.

Here in above code we are making a new folder if it doesn't exist and if it exist we are using the content in the file to display on console screen, very easy.
Put a breakpoints, run and debug.
If you like this post, please subscribe us

Comments

Popular posts from this blog

Convert your datatable into generic poco object in c# using linq, ado and reflections.

Follow @harshit_parshii The most common problem that we face these days is to create a common class and method that can be used across all the projects and codes. So today I will be sharing my code where you can see how to make and create a generic function without using entity framework for ado. net. The scenario is like you have an old software that uses stored procedure to return set of entities as a data-table, you do not want to re-write the back-end code as you are creating a web API in c# which needs to be delivered asap. You need to map these data tables to models as you might be using MV* pattern. So here we will be doing one to one mapping of model to data- table, and in similar fashion insert or update can also be done. So basically we are converting a data-table to list of strongly typed object model to do CRUD operations. So we have following things before hand. A helper class is referenced as the database(dbFactory) which executes ado. ne...

Send a Fax in windows using faxcomexlib and TAPI in VB code .Net

An application that provides sending fax from faxmodem, connected to the computer, will be explained in the following post.  We can use Telephony Application Programming Interface (TAPI) and the Fax Service Extended Component Object Model (COM) API to send fax. The fax service is a Telephony Application Programming Interface (TAPI)-compliant system service that allows users on a network to send and receive faxes from their desktop applications. The service is available on computers that are running Windows 2000 and later. The fax service provides the following features: Transmitting faxes Receiving faxes Flexible routing of inbound faxes Outbound routing Outgoing fax priorities Archiving sent and received faxes Server and device configuration management Client use of server devices for sending and receiving faxes Event logging Activity logging Delivery receipts Security permissions The following Microsoft Visual Basic code example sends a fax. Note that...

DTMF (Mobile) based speed control of AC motor.

Introduction: With the advancement of ages from prehistoric to present day scenario our life has become more sophisticated and busy, so to ease the schedule of this busy life, technology has play the vital role in it and for its proper running of machine the technology has gone further by providing digitization of analog machinery and its use is enhanced day by day. This project is based on the same concept by wireless controlling the machinery through mobile system anywhere from the world. This project aims at Speed Control of AC motor using DTMF method; DTMF stands for dual tone multiple frequencies . The main idea of this project is to control the speed of an AC motor by wireless communication using DTMF decoder technique aiming at the fine use of mobile technology in our day to day use of automated products. Mobile phones have different frequencies for each number printed on it. These numbers when pressed during call duration produces a tone of certain frequency. This frequ...