<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>C# Help &#187; I/O</title>
	<atom:link href="http://www.csharphelp.com/tag/io/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.csharphelp.com</link>
	<description>C# Tutorial and Guides</description>
	<lastBuildDate>Tue, 07 Feb 2012 01:03:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>C# Input, Output, Other File Operations, and Persisting Data</title>
		<link>http://www.csharphelp.com/2007/09/c-input-output-other-file-operations-and-persisting-data/</link>
		<comments>http://www.csharphelp.com/2007/09/c-input-output-other-file-operations-and-persisting-data/#comments</comments>
		<pubDate>Thu, 27 Sep 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[I/O]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=679</guid>
		<description><![CDATA[Welcome to the 9th tutorial in the &#34;C# for the Completely Uninitiated&#34; series. &#160; Creating Files Programmatically Reading Files Checking For File Existence Moving a File to Another Location Source code used in this tutorial: &#160; readerwriter.cs streamreader.cs char_by_char.cs file_attributes.cs file_copy.cs Creating Files Programmatically The first thing you need to know about file operations in [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack">Welcome to the 9th tutorial in the &quot;<b><span style="color:red;">C# for the Completely Uninitiated</span></b>&quot; series.</span></p>
<p>&nbsp;</p>
<ul><span class="smallblack">
<li><a href="http://www.csharphelp.com/archives4/archive704.html#creating_files">Creating Files Programmatically</a></li>
<li><a href="http://www.csharphelp.com/archives4/archive704.html#reading_files">Reading Files</a></li>
<li><a href="http://www.csharphelp.com/archives4/archive704.html#checking_existence">Checking For File Existence</a></li>
<li><a href="http://www.csharphelp.com/archives4/archive704.html#move_file">Moving a File to Another Location</a></li>
<p></span></ul>
<p><span class="smallblack">Source code used in this tutorial:</span></p>
<p>&nbsp;</p>
<ul><span class="smallblack">
<li><a href="http://www.csharphelp.com/archives4/files/archive704/readerwriter.cs" target="_blank">readerwriter.cs</a></li>
<li><a href="http://www.csharphelp.com/archives4/files/archive704/streamreader.cs" target="_blank">streamreader.cs</a></li>
<li><a href="http://www.csharphelp.com/archives4/files/archive704/char_by_char.cs" target="_blank">char_by_char.cs</a></li>
<li><a href="http://www.csharphelp.com/archives4/files/archive704/file_attributes.cs" target="_blank">file_attributes.cs</a></li>
<li><a href="http://www.csharphelp.com/archives4/files/archive704/file_copy.cs" target="_blank">file_copy.cs</a></li>
<p></span></ul>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br /></span></p>
<p><span class="smallblack"><a name="creating_files"><br />
<h4>Creating Files Programmatically</h4>
<p></a>The first thing you need to know about file operations in C#, such aswriting to a file, reading data from a file, etc., is that you mustplace a <span style="font-family:Fixedsys;">using</span> reference to <span style="font-family:Fixedsys;">System.IO</span> at the top of your source code (just beneath <span style="font-family:Fixedsys;">using System;</span> is a good place):</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/boilerplate_console.png" border="1" alt="" /></span></p>
<p><span class="smallblack">As you can see in line #2, we include areference to the System.IO namespace, which contains classes forworking with input and output.</span></p>
<p><span class="smallblack">We can add a single line of code (line #8) inside our <span style="font-family:Fixedsys;">Main()</span> method, to create a text file in our application&#39;s directory:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/srccode_file_creation.png" border="1" alt="" /></span></p>
<p><span class="smallblack">Run the program, then navigate to theapplication&#39;s executable directory under your projects folder, toconfirm that &quot;myfile.txt&quot; has indeed been created:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/confirm_file_creation.png" border="0" alt="" /></span></p>
<p><span class="smallblack">Notice that the file shows <span style="font-family:Fixedsys;">0 Kb</span>, which is what we would expect. We merely created a text file. We did <span style="text-decoration:underline;">not</span> write any data to it. The file can have any extension you want, not just <i>.txt</i>,or no extension at all, but consider that here we created a text file(see line #8 in the source code) and therefore the file is writtenusing ASCII characters. A binary file is created the same way, justthat instead of using <span style="font-family:Fixedsys;">File.CreateText()</span> you use <span style="font-family:Fixedsys;">File.Create()</span>.At first you won&#39;t notice any difference between the text file and thebinary file but it matters a lot because it is stored differently. Youuse the text file for storing text and the binary file for storingnon-text data.</span></p>
<p><span class="smallblack">Let&#39;s run the program again, but before we doso, let&#39;s update the source code so that it will actually cause thecreated text file to contain a line of text. We&#39;ll use something calleda <i>StreamWriter</i> object. This object is instantiated from a class in the <span style="font-family:Fixedsys;">System.IO</span> namespace that is used for writing data to files.</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/streamwriter_srccode.png" border="1" alt="" /></span></p>
<p><span class="smallblack">Now, run the program, then navigate to theapplication directory and examine the &quot;myfile.txt&quot; file. You&#39;ll seethat it is no longer an empty file. It should now show <span style="font-family:Fixedsys;">1 Kb</span>:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/new_file_size.png" alt="" /></span></p>
<p><span class="smallblack">If you double-click the file and examine its contents, you&#39;ll see something like the following:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/life_without_dc.png" alt="" /></span></p>
<p><span class="smallblack">It should be apparent what is going on here. With the help of a <span style="font-family:Fixedsys;">StreamWriter</span>object, we are writing a string to the text file. You could replace thestring I used, in line # 10, with any string of your choice, such as &quot;Epluribus unum&quot; or &quot;Mi casa su casa&quot;. Use the program we just wrote towrite the following line of text to the file: <span style="font-family:Fixedsys;">The name is Bond&#8230; James Bond</span>. Then exit the program and prepare to write a different program. </span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack"><a name="reading_files"><br />
<h4>Reading a Text File</h4>
<p></a>We can use C# to read either text or binary files. For the purpose ofthis introductory level tutorial, we&#39;ll only be focusing on text files.In a later tutorial, in another series altogether, I&#39;ll address writingand reading binary files.</span></p>
<p><span class="smallblack">What we&#39;re going to do now is write a programthat will open the &quot;myfile.txt&quot; text file and read the line of textthat it contains. Delete the current code in the project source codewindow, and paste <a href="http://www.csharphelp.com/archives4/files/archive704/streamreader.cs" target="_blank">this</a> source code. Run this new program, and you should see the following output:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/streamreader_output.png" alt="" /></span></p>
<p><span class="smallblack">It is also possible to read text from a file <i>one character at a time</i>. Sometimes this can be useful, although in our previous example, the <span style="font-family:Fixedsys;">ReadLine()</span> method of the <span style="font-family:Fixedsys;">StreamReader</span>class was more appropriate. However, to see how to do it by reading itone character at a time, examine the following source code listing:</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/read_each_char.png" border="1" alt="" /></span></p>
<p><span class="smallblack"> Note that we are using an integer variable to hold the value returned by each call to <span style="font-family:Fixedsys;">sr.Read()</span>;this is due to the fact that the method returns an integer value thatis the ASCII value of the character just read from the file. We thenhave to convert that ASCII value to a character (as you can see in line# 16). Probably the most complex line of code in the source codelisting shown above is line # 14. If the StreamReader object attemptsto read in a character from the file and is unsuccessful due to the endof the file having been reached, a value of negative one is returned.</span></p>
<p><span c<br />
lass="sm<br />
allblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack"><a name="checking_existence"><br />
<h4>Checking For File Existence</h4>
<p></a>If you attempt to open a file that isn&#39;t there, an exception will bethrown. Exceptions are ugly. They make users feel that your software isbuggy (not without some justification). You should check to ensure thata particular file exists on disk before attempting to open it. The <span style="font-family:Fixedsys;">System.IO</span> namespace provides the FileExists() method, which will return <span style="font-family:Fixedsys;color:blue;">true</span> if the file path you pass into the method as a parameter is valid, or <span style="font-family:Fixedsys;color:blue;">false</span>if it isn&#39;t. If your program creates a file and does not specify a pathfor it, it will, by default, be created in the directory in which theexecutable that is attempting to create the file is located. In C#projects, this will be the Debug or Release directory of the particularproject you&#39;re working on. I used this default directory in my examplesabove, where I demonstrated writing to a file, and then reading fromthat file.</span></p>
<p><span class="smallblack">You have to be careful about making assumptions when programming. You should not automatically assume that you&#39;re <i>current directory</i>is the application executable&#39;s directory, because code can change theworking directory. To demonstrate this, I&#39;ve added a single line ofcode (line #8 in the image below) to <a href="http://www.csharphelp.com/archives4/files/archive704/file_attributes.cs" target="_blank">one</a>of the example programs we did earlier. The only thing line #8 does,below, is set the current directory to somewhere other than theapplication directory (which is where our file was created). You cansee the nasty error that is caused when you assume that you&#39;re in thecorrect directory when attempting to open a file.</span></p>
<p><span class="smallblack"><img src="http://www.csharphelp.com/archives4/files/archive704/current_dir.png" border="1" alt="" /></span></p>
<p><span class="smallblack">You may not clearly understand the ratherunusual looking code in the example program for which I provide a linkabove. For example,</span></p>
<p><span class="smallblack"><span style="font-family:Fixedsys;">if ((fi.Attributes &amp; FileAttributes.ReadOnly) != 0){<br />&nbsp;&nbsp;&nbsp;// do this&#8230;<br />}</span></span></p>
<p><span class="smallblack">To break that down for you, simply know that whenever you see something in C# that looks like this:</span></p>
<p>&nbsp;</p>
<p><span class="smallblack"><span style="font-family:Fixedsys;"><br />if((BlahBlahThis &amp; BlahBlahThat) != 0) <br /></span></span>
<p><span class="smallblack">&#8230;what&#39;s being said is &quot;if it&#39;s true that thestuff inside the nested parentheses is the case, then do thefollowing&#8230;&quot; You can think of <span style="font-family:Fixedsys;">!=0</span> as &quot;not <i>not</i> the case&quot;, in other words <i>is the case</i>.</span></p>
<p><span class="smallblack">There are other attributes that we didn&#39;t usein the code but you can easily figure them out thanks to IntelliSense,if you&#39;re using the Visual C# 2005 or the Visual C# 2005 Expressedition IDE.</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack">&nbsp;</span></p>
<p><span class="smallblack"><a name="move_file"><br />
<h4>Moving a File to Another Location</h4>
<p></a>There is a method of the <span style="font-family:Fixedsys;">File</span> object named <span style="font-family:Fixedsys;">Copy()</span>. You can use it to copy a file from one location to another. <a href="http://www.csharphelp.com/archives4/files/archive704/file_copy.cs" target="_blank">This</a>source code listing shows an example of copying a file from theapplication directory to your desktop directory. Copying a file doesn&#39;teliminate the original file. If you want to <i>move</i> a file, i.e.,make it disappear from its current location and reappear in anotherdirectory, then you first copy it to the desired destination, thenfollow up by deleting it from the source directory. So, in the aboveexample, you could add the following line immediately after theinvocation of the <span style="font-family:Fixedsys;">File</span> object&#39;s <span style="font-family:Fixedsys;">Copy()</span> method, to change the program&#39;s function from <i>copying</i> to <i>moving</i> the file:</span></p>
<p><span class="smallblack"><span style="font-family:Fixedsys;">File.Delete(&quot;myfile.txt&quot;);</span> //deletes original file from the application&#39;s executable directory</span></p>
<p><span class="smallblack">In this tutorial, I&#39;ve addressed only the most basic of input and output using the <span style="font-family:Fixedsys;">System.IO</span>namespace. With a reference to this namespace, we&#39;ve been able to useinstances of the streamreader and streamwriter classes to either openan existing text file and read in its contents, or else write a newtext file to disk. You&#39;ve also been shown how to read the data from atext file one character at a time, or, alternatively, one entire lineat a time. I&#39;ve explained the importance of checking for fileexistence, and couching your read/write operations inside a try-catchblock. Although quite basic, you now have the skills to develop asimple computer roleplaying game. We&#39;ll be working on that throughoutthe next series, <span style="color:red;">&quot;C# for the Somewhat Initiated&quot;</span>,a series that introduces WinForms programming, and some programmingtips and tricks that are bit more advanced than those covered in thisseries&#39; nine tutorials.</span></p>
<p><span class="smallblack"><br /></span></p>
<hr />
<p><span class="smallblack"><br />Well, I hope that you&#39;ve benefited, at least a little, from this tutorial and, indeed, all of the tutorials in the <span style="color:red;">&quot;C# for the Completely Uninitiated&quot;</span> series. As ever, I welcome any <a href="mailto:kyrathaba@yahoo.com?subject=email%20link%20in%20kyrathaba_cs9.htm%20tutorial">feedback</a> you may wish to impart.&nbsp;</span></p>
<p><span class="smallblack"><br /></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/09/c-input-output-other-file-operations-and-persisting-data/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I/O in C# Unleased</title>
		<link>http://www.csharphelp.com/2007/08/io-in-c-unleased/</link>
		<comments>http://www.csharphelp.com/2007/08/io-in-c-unleased/#comments</comments>
		<pubDate>Sat, 01 Sep 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[I/O]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=653</guid>
		<description><![CDATA[Object &#124; \&#8212;-BinaryReader&#8212;&#8212;\ &#124; &#124;&#8211;&#62;Binary IO used to read primitive data types(int,char..) &#124;&#8212;-BinaryWriter&#8212;&#8212;/ &#124; &#124; &#124;&#8212;-Stream(Abstract) &#8212;&#62; Byte Oriented IO &#124; &#124; &#124; \ &#124; &#124;&#8212;&#8211;FileStream &#124; &#124;&#8212;&#8211;BufferedStream &#124; `&#8212;&#8211;MemoryStream &#124; &#124; &#124;&#8212;-TextReader(Abstract) &#8212;&#62; Character Based IO (For Reading&#8230;.) &#124; &#124; &#124; \ &#124; &#124;&#8212;&#8211;StreamReader &#124; `&#8212;&#8211;StringReader &#124; `&#8212;-TextWriter(Abstract) &#8212;&#62; Character Based IO (For Writing&#8230;.) [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallestblack"><span><span class="smallblack">Object<br /> |<br /> \&#8212;-BinaryReader&#8212;&#8212;\<br /> | |&#8211;&gt;Binary IO used to read primitive data types(int,char..) <br /> |&#8212;-BinaryWriter&#8212;&#8212;/<br /> |<br /> |<br /> |&#8212;-Stream(Abstract) &#8212;&gt; Byte Oriented IO <br /> | |<br /> | \<br /> | |&#8212;&#8211;FileStream<br /> | |&#8212;&#8211;BufferedStream<br /> | `&#8212;&#8211;MemoryStream<br /> |<br /> |<br /> |&#8212;-TextReader(Abstract) &#8212;&gt; Character Based IO (For Reading&#8230;.)<br /> | |<br /> | \<br /> | |&#8212;&#8211;StreamReader<br /> | `&#8212;&#8211;StringReader <br /> |<br /> `&#8212;-TextWriter(Abstract) &#8212;&gt; Character Based IO (For Writing&#8230;.)<br /> |<br /> \<br /> |&#8212;&#8211;StreamWriter<br /> `&#8212;&#8211;StringWriter </p>
<p>The Classes that are presented here are all from System.IO namespace.So make sure <br />you include it before doing IO programs.<br />#################################################################<br />To Reading Character data (ex:- reading Text Files&#8230;.)<br /> 1.Use StreamReader with File path as string in the constructor.<br /> 2.Use ReadLine() Method to read each line in the given file.<br /> 3.repeat step 2 until ReadLine() Method return null indicating end of File.<br /> 4.Close the StreamReader at Last.</p>
<p>To Writing Character data (ex:- writing Text Files&#8230;.)<br /> 1.Use StreamWriter with File path as string in the constructor.<br /> 2.Use WriteLine(&quot;&#8230;.&quot;) Method to write each line to the given file.<br /> 3.repeat step 2 until there is no data to write.<br /> 4.Close the StreamWriter at Last.</p>
<p>example:-<br />&#8212;&#8212;&#8212;<br />class IOStreams<br />{<br /> static void Main()<br /> {<br /> //Writing<br /> StreamWriter sw = new StreamWriter(@&quot;d:\a.txt&quot;);<br /> sw.WriteLine(&quot;Hai I am Vineel&#8230;&quot;);<br /> sw.WriteLine(&quot;This is from C#&quot;);<br /> sw.Close();</p>
<p> //Reading<br /> StreamReader sr = new StreamReader(@&quot;d:\a.txt&quot;);<br /> Console.WriteLine(sr.ReadLine());<br /> Console.WriteLine(sr.ReadLine());<br /> sr.Close();<br /> }<br />}<br />##############################################################<br />To Read Chunks of bytes from a file (ex:- reading few bytes from an exe file&#8230;)<br /> 1.Use FileStream with first parameter to contructor as File path(as string) <br /> and FileMode (Open,Create,Append,Truncate&#8230;) as second parameter.<br /> 2.Create an array of bytes with some size (say 1024 &#8230;) <br /> 3.Pass this array to Read Method as fs.Read(byte[],offset,count); where<br /> byte[] indicates byte array created, offset indicates from where the array<br /> should be started filling(in most cases it is Zero) and count indicates <br /> number bytes to be copied.In this case it is 1024(it can be any thing <br /> otherthan 1024);<br /> 4.When above read Method is executed you will have byte array filled with the requried <br /> data.If nothing is read in to array Read method returns zero(with which we can <br /> conclude that we have reached end of file..).The return value always indicates <br /> number of byte read in to the array.(This is not always equal to count value we have<br /> passed .For more clarity read last section in this tutorial&#8230;.)<br /> 5.If you want read once again repeat step 3<br /> 6.Close the FileStream at Last<br />**************THIS IS EXACTLY SIMILAR TO read SYSTEM CALL IN LINUX****************</p>
<p>To Write Chunks of bytes to a file (ex:- Writing few bytes to an exe file&#8230;)<br /> 1.Use FileStream with first parameter to contructor as File path(as string) <br /> and FileMode (Open,Create,Append,Truncate&#8230;) as second parameter.<br /> 2.Create an array of bytes with some size (say 1024 &#8230;) and fill it with some bytes.<br /> 3.Pass this array to Write Method as fs.Write(byte[],offset,count); where<br /> byte[] indicates byte array created, offset indicates from which offset of the array<br /> the bytes should be copied(in most cases it is Zero) and count indicates <br /> number bytes to be copied.In this case it is 1024(it can be any thing <br /> otherthan 1024);<br /> 4.When above write Method is executed you will have byte array copied to the requried <br /> file.If nothing is wrote from the array Write method returns zero(with which we can <br /> conclude that there is no data in the byte array..).The return value always indicates <br /> number of byte wrote from the array.(This is not always equal to count value we have<br /> passed .For more clarity read last section in this tutorial&#8230;.)<br /> 5.If you want write once again repeat step 3<br /> 6.Close the FileStream at Last<br />**************THIS IS EXACTLY SIMILAR TO write SYSTEM CALL IN LINUX****************<br />example:-<br />&#8212;&#8212;&#8212;<br />class IOStreams<br />{<br /> static void Main()<br /> {<br /> FileStream fs = new FileStream(@&quot;d:\xyz.exe&quot;, FileMode.OpenOrCreate);<br /> int Size = 1024;<br /> byte []data = new byte[Size];<br /> int b = fs.Read(data,0,Size);<br /> while(b!=0)<br /> {<br /> b = fs.Read(data,0,Size);<br /> //manipulate data here&#8230;.<br /> }<br /> fs.Close();<br /> }<br />}</p>
<p>####################################################################</p>
<p>To Read (or Write) primitive values from (or to) files <br /> (ex:- reading int,char,double&#8230; from files)<br /> example:-<br /> &#8212;&#8212;&#8212;<br /> //Usage of BinaryReader and BinaryWriter<br />class IOStreams<br />{<br /> static void Main()<br /> {<br /> //Writing <br /> Stream sin = new FileStream(@&quot;d:\a.txt&quot;, FileMode.Create);<br /> BinaryWriter bw = new BinaryWriter(sin);<br /> bw.Write(124);<br /> bw.Write(&quot;Vineel&quot;);<br /> bw.Close();<br /> sin.Close();</p>
<p> //Reading<br /> Stream sout = new FileStream(@&quot;d:\a.txt&quot;, FileMode.Open);<br /> BinaryReader br = new BinaryReader(sout);<br /> Console.WriteLine(br.ReadInt32());<br /> Console.WriteLine(br.ReadString());<br /> br.Close();<br /> sout.Close();<br /> }<br />}<br /> Open the created text file in Notepad and see.You will find only cryptic characters <br /> not the values inserted.But what is amazing is the data wrote to the file is exactly<br /> read back by BinaryReader even though we cannot recognise it manually.<br />########################################################################## </p>
<p>CHOOSING WHICH CLASSES TO USE WHEN<br />&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />1.Most probably when you want to manipulate a text file for example copying it or reading<br /> from it go for StreamReader and StreamWriter<br />2.When you want to manipulate byte files like MP3,EXE files for example extracting bitrate<br /> from an MP3 file or even copying to MP3 Files go for FileStream.<br />3.Finally storing data in predefined sequence and also to retriving it in that sequence<br /> for example student details like RollNumber(int),Name(String), FeePaid(double) .e.t.c<br /> go for BinaryReader and BinaryWriter because they make reading process easier without<br /> we worrying about how the data is stored in the file.In this case we can simply call<br /> br.ReadInt32() for RollNumber,br.ReadString() for Name,br.ReadDouble() for FeePaid to<br /> get the data stored.<br />##########################################################################</p>
<p>return values from Read or Write methods need not always equal to their count parameter <br />&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br />Consider a file having 25 bytes and if we are reading(writing) it in a bulk of 10 bytes<br />(means count=10) we need to call Read (or Write) method 3 times.In first two Read(or Write) <br />calls the value returned is equal to count value . But now when these two Read (or Write)<br />calls completed we have only 5 more bytes to read (or write) so at this point <br />even though the Read (or Write) method is supposed to read (Or write) 10 bytes it will <br />only read (Or write) 5 bytes and accordingly the return value is only 5 in this case &#8230;.<br />&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</p>
<p>There are many more classes in .NET Framework concerned with IO.Only basic<br />
classes<<br />
br />are dealt here.<br /></span></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/08/io-in-c-unleased/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Open and Read a File in Win Forms using C#</title>
		<link>http://www.csharphelp.com/2007/07/how-to-open-and-read-a-file-in-win-forms-using-c/</link>
		<comments>http://www.csharphelp.com/2007/07/how-to-open-and-read-a-file-in-win-forms-using-c/#comments</comments>
		<pubDate>Sun, 29 Jul 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[I/O]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=619</guid>
		<description><![CDATA[In this tutorial I am going to tell you abouthow to open your file and display it in the text box and how to saveyour file anywhere . HOW TO OPEN (READ) A FILE Open your new project and name it &#34;filestream&#34;,then create a button and in properties change its text to &#34;open textfile to [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack">In this tutorial I am going to tell you abouthow to open your file and display it in the text box and how to saveyour file anywhere .</span></p>
<p><span class="smallblack">HOW TO OPEN (READ) A FILE</span></p>
<p><span class="smallblack">Open your new project and name it &quot;filestream&quot;,then create a button and in properties change its text to &quot;open textfile to read&quot; and its name to &quot;btn1&quot;.<br />Then double click on option in the toolbar named &quot;open file dialog&quot;,immediately the in the form design the &quot;OpenFileDialog1&quot; will appearbelow. </span></p>
<p><span class="smallblack">Also Create simple text box and in properties change its text to blank and its name to &quot;text box1&quot;.</span></p>
<p><span class="smallblack">Also add label to text box where you can giveinstructions to the user that what to do with the text box.Now double click the button &quot;open text file to read&quot; and then add thelibrary &quot;using System.IO&quot; .After this make a following function in theclass as:</span></p>
<p><span class="smallblack">private string Read( string file )<br />{</p>
<p> StreamReader reader = new StreamReader( file );<br /> string data = reader.ReadToEnd ();<br /> reader.Close();</p>
<p> return data;<br />}<br /></span>
<p><span class="smallblack">The explanation of this code is very simple.here we have just created a Read function and give it the parameter&quot;file&quot; of type string (so that whatever in the file is read as a stringof characters).in the braces we write the code of reading from the textfile .here StreamReader is associated with System.IO class ,we havecreated object of StreamReader and reserved space for the file with newkeyword ,then we read that file from start to end and stored it in thedata variable of type string, and return that data.After adding this code we will ad the following code in the buttonfunction..</span></p>
<p><span class="smallblack"> </span></p>
<p><span class="smallblack">textBox1.Text = &quot;&quot;; <br />DialogResult result = openFileDialog1.ShowDialog();<br />if ( result == DialogResult.OK )<br />{<br /> string data = Read( openFileDialog1.FileName );<br /> textBox1.Text = data;<br />}<br />else<br />{</p>
<p> //do nothing<br />}<br /></span>
<p><span class="smallblack"> In the above code we have justcleared the textbox by &quot;textBox1.Text = &quot;&quot;&quot;.then in the next statementwe opened the dialog box &quot;DialogResult result=openFileDialog1.ShowDialog()&quot; .In the next statement we used if elsestatement to ensure if the user has selected the file then immediatelythe Read() function will be called(which we have created above) and itwill read from the file and store that contents of the file in thevariable of type &quot;string&quot;, and display it in the text box and if userdoesn&#39;t select the text file then do nothing.</span></p>
<p><span class="smallblack">HOW TO SAVE FILE</span></p>
<p><span class="smallblack">Now I am going to tell you about how to saveyour file where ever you want in windows forms . Firstly go to the toolbar and double click on option named &quot;SaveFileDialog&quot;(same procedure asabove).Then Create a button and in properties set its text to &quot;Saveyour file(write extension also)&quot; and its name to &quot;btn2&quot;.Double click onthis button and write following function in the class..</span></p>
<p><span class="smallblack">private void Save( string file, string data )<br />{<br /> StreamWriter writer = new StreamWriter(file);<br /> writer.Write(data);<br /> writer.Close();<br />}<br /></span>
<p><span class="smallblack">in the above code we have created the functionsave and passed two parameters in it of type string ,next in the braceswe simply write code for writing in the file .here Stream Writer(similar to StreamReader) is associated with the library System.IO.</span></p>
<p><span class="smallblack">After this add the following code in the button function..</span></p>
<p><span class="smallblack">DialogResult result = saveFileDialog1.ShowDialog();</p>
<p>string file=saveFileDialog1.FileName.ToString();<br />string data = textBox1.Text;<br />Save( file, data );<br /></span>
<p><span class="smallblack">In the above code when user click on savebutton then the save dialog will appear where file name is enterednormally in the dialog box and stored in the variable &quot;file&quot; of typestring and contents of the text box which is entered by the user isstored in variable of type &quot;data&quot;.<br />Then on clicking save button in dialog Box the file will be saved.. </span></p>
<p><span class="smallblack">Author: BASEER AHMED<br />Student of: (Bachelor of science in telecommunication engineering)<br />National university of computer and emerging sciences (FAST)<br />Pakistan.<br />E-mail: baseerhmd@gmail.com<br /></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/07/how-to-open-and-read-a-file-in-win-forms-using-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>File Copier &#8211; WinForms Demonstration Program</title>
		<link>http://www.csharphelp.com/2007/06/file-copier-winforms-demonstration-program/</link>
		<comments>http://www.csharphelp.com/2007/06/file-copier-winforms-demonstration-program/#comments</comments>
		<pubDate>Sat, 30 Jun 2007 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Win Forms]]></category>
		<category><![CDATA[I/O]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=590</guid>
		<description><![CDATA[Here is source for a file copier program that uses WinForms. using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Windows.Forms;/// &#60;remarks&#62;/// File Copier &#8211; WinForms demonstration program/// (c) Copyright 2001 Liberty Associates, Inc./// &#60;/remarks&#62;namespace FileCopier{ /// &#60;summary&#62; /// Form demonstrating Windows Forms implementation /// &#60;/summary&#62; // &#60; declarations of Windows widgets cut here &#62; public class [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack">Here is source for a file copier program that uses WinForms.</span></p>
<p><span class="smallblack">using System;<br />using System.Collections;<br />using System.ComponentModel;<br />using System.Data;<br />using System.Drawing;<br />using System.IO;<br />using System.Windows.Forms;<br />/// &lt;remarks&gt;<br />/// File Copier &#8211; WinForms demonstration program<br />/// (c) Copyright 2001 Liberty Associates, Inc.<br />/// &lt;/remarks&gt;<br />namespace FileCopier<br />{<br /> /// &lt;summary&gt;<br /> /// Form demonstrating Windows Forms implementation<br /> /// &lt;/summary&gt;<br /> // &lt; declarations of Windows widgets cut here &gt;<br /> public class Form1 : System.Windows.Forms.Form<br /> {<br /> /// &lt;summary&gt;<br /> /// internal class which knows how to compare<br /> /// two files we want to sort large to small,<br /> /// so reverse the normal return values.<br /> /// &lt;/summary&gt;<br /> public class FileComparer : IComparer<br /> {<br /> public int Compare (object f1, object f2)<br /> {<br /> FileInfo file1 = (FileInfo) f1;<br /> FileInfo file2 = (FileInfo) f2;<br /> if (file1.Length &gt; file2.Length)<br /> {<br /> return -1;<br /> }<br /> if (file1.Length &lt; file2.Length)<br /> {<br /> return 1;<br /> }<br /> return 0;<br /> }<br /> }<br /> public Form1( )<br /> {<br /> //<br /> // Required for Windows Form Designer support<br /> //<br /> InitializeComponent( );<br /> // fill the source and target directory trees<br /> FillDirectoryTree(tvwSource, true);<br /> FillDirectoryTree(tvwTargetDir, false);<br /> }<br /> /// &lt;summary&gt;<br /> /// Fill the directory tree for either the Source or<br /> /// Target TreeView.<br /> /// &lt;/summary&gt;<br /> private void FillDirectoryTree(<br /> TreeView tvw, bool isSource)<br /> {<br /> // Populate tvwSource, the Source TreeView,<br /> // with the contents of<br /> // the local hard drive.<br /> // First clear all the nodes.<br /> tvw.Nodes.Clear( );<br /> // Get the logical drives and put them into the<br /> // root nodes. Fill an array with all the<br /> // logical drives on the machine.<br /> string[] strDrives =<br /> Environment.GetLogicalDrives( );<br /> // Iterate through the drives, adding them to the tree.<br /> // Use a try/catch block, so if a drive is not ready,<br /> // e.g. an empty floppy or CD,<br /> // it will not be added to the tree.<br /> foreach (string rootDirectoryName in strDrives)<br /> {<br /> if (rootDirectoryName != @\&quot;C:\\&quot;)<br /> continue;<br /> try<br /> {<br /> // Fill an array with all the first level<br /> // subdirectories. If the drive is<br /> // not ready, this will throw an exception.<br /> DirectoryInfo dir =<br /> new DirectoryInfo(rootDirectoryName);<br /> dir.GetDirectories( );<br /> TreeNode ndRoot = new TreeNode(rootDirectoryName);<br /> // Add a node for each root directory.<br /> tvw.Nodes.Add(ndRoot);<br /> // Add subdirectory nodes.<br /> // If TreeView is the source,<br /> // then also get the filenames.<br /> if (isSource)<br /> {<br /> GetSubDirectoryNodes(<br /> ndRoot, ndRoot.Text, true);<br /> }<br /> else<br /> {<br /> GetSubDirectoryNodes(<br /> ndRoot, ndRoot.Text, false);<br /> }<br /> }<br /> catch (Exception e)<br /> {<br /> // Catch any errors such as<br /> // Drive not ready.<br /> MessageBox.Show(e.Message);<br /> }<br /> }<br /> } // close for FillSourceDirectoryTree<br /> /// &lt;summary&gt;<br /> /// Gets all the subdirectories below the<br /> /// passed in directory node.<br /> /// Adds to the directory tree.<br /> /// The parameters passed in at the parent node<br /> /// for this subdirectory,<br /> /// the full pathname of this subdirectory,<br /> /// and a Boolean to indicate<br /> /// whether or not to get the files in the subdirectory.<br /> /// &lt;/summary&gt;<br /> private void GetSubDirectoryNodes(<br /> TreeNode parentNode, string fullName, bool getFileNames)<br /> {<br /> DirectoryInfo dir = new DirectoryInfo(fullName);<br /> DirectoryInfo[] dirSubs = dir.GetDirectories( );<br /> // Add a child node for each subdirectory.<br /> foreach (DirectoryInfo dirSub in dirSubs)<br /> {<br /> // do not show hidden folders<br /> if ( (dirSub.Attributes &amp; FileAttributes.Hidden)<br /> != 0 )<br /> {<br /> continue;<br /> }<br /> /// &lt;summary&gt;<br /> /// Each directory contains the full path.<br /> /// We need to split it on the backslashes,<br /> /// and only use<br /> /// the last node in the tree.<br /> /// Need to double the backslash since it<br /> /// is normally<br /> /// an escape character<br /> /// &lt;/summary&gt;<br /> TreeNode subNode = new TreeNode(dirSub.Name);<br /> parentNode.Nodes.Add(subNode);<br /> // Call GetSubDirectoryNodes recursively.<br /> GetSubDirectoryNodes(<br /> subNode,dirSub.FullName,getFileNames);<br /> }<br /> if (getFileNames)<br /> {<br /> // Get any files for this node.<br /> FileInfo[] files = dir.GetFiles( );<br /> // After placing the nodes,<br /> // now place the files in that subdirectory.<br /> foreach (FileInfo file in files)<br /> {<br /> TreeNode fileNode = new TreeNode(file.Name);<br /> parentNode.Nodes.Add(fileNode);<br /> }<br /> }<br /> }<br /> // &lt; boilerplate code cut here &gt;<br /> /// &lt;summary&gt;<br /> /// The main entry point for the application.<br /> /// &lt;/summary&gt;<br /> [STAThread]<br /> static void Main( )<br /> {<br /> Application.Run(new Form1( ));<br /> }<br /> /// &lt;summary&gt;<br /> /// Create an ordered list of all<br /> /// the selected files, copy to the<br /> /// target directory<br /> /// &lt;/summary&gt;<br /> private void btnCopy_Click(object sender,<br /> System.EventArgs e)<br /> {<br /> // get the list<br /> ArrayList fileList = GetFileList( );<br /> // copy the files<br /> foreach (FileInfo file in fileList)<br /> {<br /> try<br /> {<br /> // update the label to show progress<br /> lblStatus.Text = \&quot;Copying \&quot; + txtTargetDir.Text +<br /> \&quot;\\\&quot; + file.Name + \&quot;&#8230;\&quot;;<br /> Application.DoEvents( );<br /> // copy the file to its destination location<br /> file.CopyTo(txtTargetDir.Text + \&quot;\\\&quot; +<br /> file.Name,chkOverwrite.Checked);<br /> }<br /> catch // (Exception ex)<br /> {<br /> // you may want to do more than just show the message<br /> // MessageBox.Show(ex.Message);<br /> }<br /> }<br /> lblStatus.Text = \&quot;Done.\&quot;;<br /> Application.DoEvents( );<br /> }<br /> /// &lt;summary&gt;<br /> /// on cancel, exit<br /> /// &lt;/summary&gt;<br /> private void btnCancel_Click(object sender, System.EventArgs e)<br /> {<br /> Application.Exit( );<br /> }<br /> /// &lt;summary&gt;<br /> /// Tell the root of each tree to uncheck<br /> /// all the nodes below<br /> /// &lt;/summary&gt;<br /> private void btnClear_Click(object sender, System.EventArgs e)<br /> {<br /> // get the top most node for each drive<br /> // and tell it to clear recursively<br /> foreach (TreeNode node in tvwSource.Nodes)<br /> {<br /> SetCheck(node, false);<br /> }<br /> }<br /> /// &lt;summary&gt;<br /> /// check that the user does want to delete<br /> /// Make a list and delete each in turn<br /> /// &lt;/summary&gt;<br /> private void btnDelete_Click(object sender, System.EventArgs e)<br /> {<br /> // ask them if they are sure<br /> System.Windows.Forms.DialogResult result =<br /> MessageBox.Show(<br /> \&quot;Are you quite sure?\&quot;, // msg<br /> \&quot;Delete Files\&quot;, // caption<br /> MessageBoxButtons.OKCancel, // buttons<br /> MessageBoxIcon.Exclamation, // icons<br /> MessageBoxDefaultButton.Button2); // default button<br /> // if they are sure&#8230;<br /> if (result == System.Windows.Forms.DialogResult.OK)<br /> {<br /> // iterate through the list and delete them.<br /> // get the list of selected files<br /> ArrayList fileNames = GetFileList( );<br /> foreach (FileInfo file in fileNames)<br /> {<br /> try<br /> {<br /> // update the label to show progress<br /> lblStatus.Text = \&quot;Deleting \&quot; +<br /> txtTargetDir.Text + \&quot;\\\&quot; +<br /> file.Name + \&quot;&#8230;\&quot;;<br /> Application.DoEvents( );<br /> // Danger Will Robinson!<br /> file.Delete( );<br /> }<br /> catch (Exception ex)<br /> {<br /> //<br />
you may<br />
want to do more than<br /> // just show the message<br /> MessageBox.Show(ex.Message);<br /> }<br /> }<br /> lblStatus.Text = \&quot;Done.\&quot;;<br /> Application.DoEvents( );<br /> }<br /> }<br /> /// &lt;summary&gt;<br /> /// Get the full path of the chosen directory<br /> /// copy it to txtTargetDir<br /> /// &lt;/summary&gt;<br /> private void tvwTargetDir_AfterSelect(<br /> object sender,<br /> System.Windows.Forms.TreeViewEventArgs e)<br /> {<br /> // get the full path for the selected directory<br /> string theFullPath = GetParentString(e.Node);<br /> // if it is not a leaf, it will end with a backslash<br /> // remove the backslash<br /> if (theFullPath.EndsWith(\&quot;\\\&quot;))<br /> {<br /> theFullPath =<br /> theFullPath.Substring(0,theFullPath.Length-1);<br /> }<br /> // insert the path in the text box<br /> txtTargetDir.Text = theFullPath;<br /> }<br /> /// &lt;summary&gt;<br /> /// Mark each node below the current<br /> /// one with the current value of checked<br /> /// &lt;/summary&gt;<br /> private void tvwSource_AfterCheck(object sender,<br /> System.Windows.Forms.TreeViewEventArgs e)<br /> {<br /> // Call a recursible method.<br /> // e.node is the node which was checked by the user.<br /> // The state of the check mark is already<br /> // changed by the time you get here.<br /> // Therefore, we want to pass along<br /> // the state of e.node.Checked.<br /> SetCheck(e.Node,e.Node.Checked);<br /> }<br /> /// &lt;summary&gt;<br /> /// recursively set or clear check marks<br /> /// &lt;/summary&gt;<br /> private void SetCheck(TreeNode node, bool check)<br /> {<br /> // set this node&#39;s check mark<br /> node.Checked = check;<br /> // find all the child nodes from this node<br /> foreach (TreeNode n in node.Nodes)<br /> {<br /> // if the child is a leaf<br /> // just check it (or uncheck it)<br /> if (node.Nodes.Count == 0)<br /> {<br /> node.Checked = check;<br /> }<br /> // if the child is a node in the tree, recurse<br /> else<br /> {<br /> SetCheck(n,check);<br /> }<br /> }<br /> }<br /> /// &lt;summary&gt;<br /> /// Given a node and an array list<br /> /// fill the list with the names of<br /> /// all the checked files<br /> /// &lt;/summary&gt;<br /> // Fill the ArrayList with the full paths of<br /> // all the feils checked<br /> private void GetCheckedFiles(TreeNode node,<br /> ArrayList fileNames)<br /> {<br /> // if this is a leaf&#8230;<br /> if (node.Nodes.Count == 0)<br /> {<br /> // if the node was checked&#8230;<br /> if (node.Checked)<br /> {<br /> // get the full path and add it to the arrayList<br /> string fullPath = GetParentString(node);<br /> fileNames.Add(fullPath);<br /> }<br /> }<br /> else // if this node is not a leaf<br /> {<br /> // call this for all the subnodes<br /> foreach (TreeNode n in node.Nodes)<br /> {<br /> GetCheckedFiles(n,fileNames);<br /> }<br /> }<br /> }<br /> /// &lt;summary&gt;<br /> /// Given a node, return the<br /> /// full pathname<br /> /// &lt;/summary&gt;<br /> private string GetParentString(TreeNode node)<br /> {<br /> // if this is the root node (c:\) return the text<br /> if(node.Parent == null)<br /> {<br /> return node.Text;<br /> }<br /> else<br /> {<br /> // recurse up and get the path then<br /> // add this node and a slash<br /> // if this node is the leaf, don&#39;t add the slash<br /> return GetParentString(node.Parent) + node.Text +<br /> (node.Nodes.Count == 0 ? \&quot;\&quot; : \&quot;\\\&quot;);<br /> }<br /> }<br /> /// &lt;summary&gt;<br /> /// shared by delete and copy<br /> /// creates an ordered list of all<br /> /// the selected files<br /> /// &lt;/summary&gt;<br /> private ArrayList GetFileList( )<br /> {<br /> // create an unsorted array list of the full filenames<br /> ArrayList fileNames = new ArrayList( );<br /> // fill the fileNames ArrayList with the<br /> // full path of each file to copy<br /> foreach (TreeNode theNode in tvwSource.Nodes)<br /> {<br /> GetCheckedFiles(theNode, fileNames);<br /> }<br /> // Create a list to hold the fileInfo objects<br /> ArrayList fileList = new ArrayList( );<br /> // for each of the filenames we have in our unsorted list<br /> // if the name corresponds to a file (and not a directory)<br /> // add it to the file list<br /> foreach (string fileName in fileNames)<br /> {<br /> // create a file with the name<br /> FileInfo file = new FileInfo(fileName);<br /> // see if it exists on the disk<br /> // this fails if it was a directory<br /> if (file.Exists)<br /> {<br /> // both the key and the value are the file<br /> // would it be easier to have an empty value?<br /> fileList.Add(file);<br /> }<br /> }<br /> // Create an instance of the IComparer interface<br /> IComparer comparer = (IComparer) new FileComparer( );<br /> // pass the comparer to the sort method so that the list<br /> // is sorted by the compare method of comparer.<br /> fileList.Sort(comparer);<br /> return fileList;<br /> }<br /> }<br />}<br />/// &lt;summary&gt;<br />/// Mark each node below the current<br />/// one with the current value of checked<br />/// &lt;/summary&gt;<br />protected void tvwSource_AfterCheck (<br />object sender, System.Windows.Forms.TreeViewEventArgs e)<br />{<br />}<br /></span>
<p><span class="smallblack">C:\Documents and Settings\Nikola\MyDocuments\Visual Studio Projects\WindowsApplication1\Form1.cs(420): Anamespace does not directly contain members such as fields or methods</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2007/06/file-copier-winforms-demonstration-program/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with System.IO.Directory Class in C#</title>
		<link>http://www.csharphelp.com/2006/10/working-with-system-io-directory-class-in-c/</link>
		<comments>http://www.csharphelp.com/2006/10/working-with-system-io-directory-class-in-c/#comments</comments>
		<pubDate>Mon, 30 Oct 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[I/O]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=347</guid>
		<description><![CDATA[Introduction This article is focused on understanding the Directory class of System.IO namespace. The Directory class exposes routines for manipulating directories &#38; subdirectories. It contains all kinds of routines like creating, moving, and enumerating through directories and subdirectories. In most of the application developments we require some file accesses or directory accesses normally we use [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"></span></p>
<p><span class="smallblack">Introduction</span></p>
<p><span class="smallblack">This article is focused on understanding the Directory class of System.IO namespace. The Directory class exposes routines for manipulating directories &amp; subdirectories. It contains all kinds of routines like creating, moving, and enumerating through directories and subdirectories. In most of the application developments we require some file accesses or directory accesses normally we use some low-level system API like Directory-Control Routines in C (ex:- _mkdir, _chdir, _rmdir) or Platform SDK function of Kernel32.lib (ex:- CreateDirectory(),SetCurrentDirectory(),RemoveDirectory()). In .net we have System.IO.Directory class to do all directory manipulation. For better understanding I will compare code with some C &amp; SDK programs. You will see how easy it is in C# when compared to old programming languages.</span></p>
<p><span class="smallblack">Let take a small example to get all the available drive information (this includes both physical &amp; logical drives).</span></p>
<p><span class="smallestblack"><span class="smallblack">Using C routines<br />&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />#include &lt;stdio.h&gt;<br />#include &lt;conio.h&gt;<br />#include &lt;direct.h&gt;<br />#include &lt;stdlib.h&gt;<br />#include &lt;ctype.h&gt;<br />void main( void )<br />{<br /> int drive, curdrive;<br /> static char path[_MAX_PATH];</p>
<p> /* Save current drive. */<br /> curdrive = _getdrive();</p>
<p> printf( &quot;Using C routines, Available drives <br />are: \n&quot; );</p>
<p> /* If we can switch to the drive, it exists. */<br /> for( drive = 1; drive &lt;= 26; drive++ )<br /> if( !_chdrive( drive ) )<br /> printf( &quot;%c: \n&quot;, drive + &#39;A&#39; &#8211; 1 );<br />}</p>
<p>Output:<br />Using C routines, Available drives are:<br />A:\<br />C:\<br />D:\<br />E:\<br />Z:\</p>
<p>Using Platform SDK File I/O routines<br />&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;<br />#include &lt;windows.h&gt;<br />#include &lt;stdio.h&gt;<br />void main( void )<br />{<br /> char *lpBuffer=new char[1000];<br /> long retSize;</p>
<p>retSize=GetLogicalDriveStrings(1000,lpBuffer<br />);<br />printf(&quot;Using SDK routines, Available drives <br />are:\n&quot;);</p>
<p> for(int i=0;i&lt;=retSize;i++)<br /> {<br />	 if(lpBuffer[i]!=&#39;\0&#39;)<br />		 printf(&quot;%c&quot;,lpBuffer[i]);<br />	 else<br />		 printf(&quot;\n&quot;);<br /> }<br />}</p>
<p>Output:<br />Using SDK routines, Available drives are:<br />A:\<br />C:\<br />D:\<br />E:\<br />Z:\</p>
<p>The same program we will do in C#</p>
<p>GetDr.cs<br />using System;<br />using System.IO;</p>
<p>class getDr<br />{<br /> public static void Main()<br /> {<br /> try<br /> {<br /> string[] str=Directory.GetLogicalDrives();<br /> Console.WriteLine( &quot;Using C# Directory Class ,Available drives are:&quot;);<br /> for(int i=0;i&lt; str.Length;i++)<br /> Console.WriteLine(str[i]);<br /> }catch(IOException e) { Console.WriteLine(e.ToString()); }</p>
<p> } // end of Main<br />}//end of Class</p>
<p>Output:<br />Using C# Directory Class, Available drives are:<br />A:\<br />C:\<br />D:\<br />E:\<br />Z:\<br />&lt;/stdio.h&gt;&lt;/windows.h&gt;&lt;/ctype.h&gt;&lt;/stdlib.h&gt;&lt;/direct.h&gt;&lt;/conio.h&gt;&lt;/stdio.h&gt;</span>
<p><span class="smallblack">So lets understand how this works System.IO.Directory class has method called GetLogicalDrives() this method returns all available drives in your system as array of strings. Before that some important thing to remember is all methods of the Directory class are static and can therefore be called without having an instance of a directory. The static methods of the Directory class do a security check on all methods. If you are going to reuse an object several times, consider using the corresponding instance method of DirectoryInfo instead, because the security check will not always be necessary.</span></p>
<p><span class="smallblack">Now that we know about Directory class so we will examine the IL code of C# sample (getDr.exe) and also System.IO library.</span></p>
<p><span class="smallblack">(IL code of sample code getDr.exe)<br />IL_0000:call string[] [&#39;mscorlib&#39;]&#39;System.IO&#39;.&#39;Directory&#39;::&#39;GetLogicalDrives&#39;()<br /> |<br /> V <br />(IL code of System.IO library)<br />IL_000b: call int32 Microsoft.Win32.Win32Native::GetLogicalDrives()<br /> |<br /> V <br />(IL code of System.IO library)<br />.method assembly hidebysig static pinvokeimpl(&quot;kernel32.dll&quot; lasterr winapi) <br /> int32 GetLogicalDrives() cil managed preservesig<br />{ }<br /></span>
<p><span class="smallblack">If you see the above IL code of System.IO library it internally calls the kernel32.dll GetLogicalDrives() which is nothing but File I/O function in Kernel32.dll library which retrieves a bitmask representing the currently available disk drives. When you call Directory Class methods of System.IO library it internally pinvokes the Microsoft Win32 native functions (see the above Platform SDK code).Similarly we will see a sample code to create and change directory. For this sample code we will be using Directory.CreateDirectory(), Directory.GetCurrentDirectory() ,Directory.Delete(), Directory.Exists() and Directory.SetCurrentDirectory().</span></p>
<p><span class="smallestblack"><span class="smallblack">chgDr.cs<br />using System;<br />using System.IO;<br />class chgDr<br />{<br /> public static void Main()<br /> {<br /> try<br /> {<br /> Console.WriteLine(&quot;&#8211;&gt;Your Current Directory&quot;);<br /> String curDir=Directory.GetCurrentDirectory();<br /> Console.WriteLine(curDir);<br /> String newDir=&quot;TestDir&quot;;<br /> Directory.CreateDirectory(newDir);<br /> Console.WriteLine(&quot;&#8211;&gt; &#39;&quot; + newDir + &quot;&#39; Directory created&quot;);<br /> Directory.SetCurrentDirectory(newDir);<br /> Console.WriteLine(&quot;&#8211;&gt; Changing to &#39;&quot; + newDir + &quot;&#39; Directory &quot;);<br /> Console.WriteLine(Directory.GetCurrentDirectory());<br /> Console.WriteLine(&quot;&#8211;&gt; Changing to &#39;&quot; + curDir + &quot;&#39; Directory &quot;);<br /> Directory.SetCurrentDirectory(curDir);<br /> Console.WriteLine(Directory.GetCurrentDirectory());<br /> Console.WriteLine(&quot;&#8211;&gt; Deleting &#39;&quot; + newDir + &quot;&#39; Directory &quot;);<br /> if(Directory.Exists(newDir))<br /> Directory.Delete(newDir);<br /> Console.WriteLine(&quot;&#8211;&gt; Checking &#39;&quot; + newDir + &quot;&#39; Directory Exists or not&quot;);</p>
<p> if(!Directory.Exists(newDir))<br /> Console.WriteLine(&quot;&#39;&quot; + newDir + &quot;&#39; Does not exists &quot;);<br /> }catch(IOException e){ Console.WriteLine(e.ToString()); }<br /> }</p>
<p>}</p>
<p>Output:<br />D:\samples\vstudio&gt;chgDr<br />&#8211;&gt;Your Current Directory<br />D:\samples\vstudio<br />&#8211;&gt; &#39;TestDir&#39; Directory created<br />&#8211;&gt; Changing to &#39;TestDir&#39; Directory<br />D:\samples\vstudio\TestDir<br />&#8211;&gt; Changing to &#39;D:\samples\vstudio&#39; Directory<br />D:\samples\vstudio<br />&#8211;&gt; Deleting &#39;TestDir&#39; Directory<br />&#8211;&gt; Checking &#39;TestDir&#39; Directory Exists or not<br />&#39;TestDir&#39; Does not exists<br /></span>
<p><span class="smallblack">Some points to remember:<br />a)	Path names are limited to 248 characters</span></p>
<p><span class="smallblack">b)	The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name.</span></p>
<p><span class="smallblack">c)	Ensure that your paths are well-formed when using methods that accept a path string .In C# path names should have \\ instead of single \ </span></p>
<p><span class="smallblack">d)	If you don&#39;t have permission it will generate FileIOPermission exception.</span></p>
<p><span class="smallblack">Further reading <br />1.	.Net More information on .Net technologies </span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/10/working-with-system-io-directory-class-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manipulating Files With C#</title>
		<link>http://www.csharphelp.com/2006/06/manipulating-files-with-c/</link>
		<comments>http://www.csharphelp.com/2006/06/manipulating-files-with-c/#comments</comments>
		<pubDate>Wed, 07 Jun 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[I/O]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=202</guid>
		<description><![CDATA[This is a simple program that shows a bit ofhow to manipulate files in Visual C#.Net.I developed this as a &#34;C# Console Application&#34; and this simple programacts like a &#34;DOS&#34; operating system. The only file needed for theapplication is the &#34;MyClass.cs&#34;. Open the &#34;ReadMe&#34; file in the zippedfile to see it&#39;s usage. Download FileManipulation.zip]]></description>
			<content:encoded><![CDATA[<p><span style="font-size:xx-small;"><b><br /></b></span><span class="smallblack"><a href="mailto:gildeoni@hotmail.com"></a></span></p>
<p><span class="smallblack">This is a simple program that shows a bit ofhow to manipulate files in Visual C#.Net.I developed this as a &quot;C# Console Application&quot; and this simple programacts like a &quot;DOS&quot; operating system. The only file needed for theapplication is the &quot;MyClass.cs&quot;. Open the &quot;ReadMe&quot; file in the zippedfile to see it&#39;s usage.</span></p>
<p><span class="smallblack">Download <a href="http://www.csharphelp.com/archives/files/archive209/FileManipulation.zip">FileManipulation.zip</a></span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/06/manipulating-files-with-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>TextReader and TextWriter In C#</title>
		<link>http://www.csharphelp.com/2006/04/textreader-and-textwriter-in-c/</link>
		<comments>http://www.csharphelp.com/2006/04/textreader-and-textwriter-in-c/#comments</comments>
		<pubDate>Mon, 10 Apr 2006 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[I/O]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=144</guid>
		<description><![CDATA[INTRODUCTION: This article covers the information of how toread or write (Unicode) character based data through TextReader andTextWriter. The TextReader and TextWriter are base classes. TheStreamReader and StringReader derives from the abstract typeTextReader. Similarly the StreamWriter and StringWriter derives fromthe abstract type TextWriter. STREAMWRITERS &#38; STREAMREADERS: As I mentioned earlier StreamWriter typederives from a base [...]]]></description>
			<content:encoded><![CDATA[<p><span style="font-size: xx-small;"><strong><br />
</strong></span><span class="smallblack"><a href="mailto:ggarung@rediffmail.com"></a></span></p>
<p><span class="smallblack">INTRODUCTION:</span></p>
<p><span class="smallblack">This article covers the information of how toread or write (Unicode) character based data through TextReader andTextWriter. The TextReader and TextWriter are base classes. TheStreamReader and StringReader derives from the abstract typeTextReader. Similarly the StreamWriter and StringWriter derives fromthe abstract type TextWriter.</span></p>
<p><span class="smallblack">STREAMWRITERS &amp; STREAMREADERS:</span></p>
<p><span class="smallblack">As I mentioned earlier StreamWriter typederives from a base class named TextWriter. This class defines membersthat allow derived types to write textual data to a given characterstream.</span></p>
<p><span class="smallblack">Let us see some of the main members of the abstract class TextWriter.</span></p>
<p><span class="smallblack">1.close() &#8212; Closes the Writer and frees any associated resources.<br />
2.Write() &#8212; Writes a line to the text stream, with out a newline.<br />
3.WriteLine() &#8212; Writes a line to the text stream, with a newline.<br />
4.Flush() &#8212; Clears all buffers.</span></p>
<p><span class="smallblack">WRITING &#8211; TEXT FILE:</span></p>
<p><span class="smallblack">Let us see the Writing to a Text File with a example.</span></p>
<p><span class="smallblack">Before we move into writing to a text file wehave to know about &#8220;FileInfo&#8221; class. What is FileInfo? In the frameworkof .NET , the system.IO namespace is the region of the base classlibraries devoted to file-based input and output services.File Info isone of the core type of System.IO Namespace.The function of the FileInfo is to encapsulate a number of detailsregarding existing files on your hard drive (size,fileattributes,creating time,etc.)as well as aid in the creation anddestruction of new files. Let us move to example.</span></p>
<p><span class="smallblack">In this example in the Writetextfile class Icreate a file named &#8220;Arungg.txt&#8221; using the FileInfo class. Aftercreating the text file using the CreateText() method, I get aStreamWriter and write some textual data to the newly created textfile. We can also add numeric data into the text file.</span></p>
<p><span class="smallblack">public class Writetextfile</span></p>
<p>{<br />
public static int Main(sting[] args)<br />
{<br />
FileInfo t = new FileInfo(&#8220;Arungg.txt&#8221;);<br />
StreamWriter Tex =f.CreateText();<br />
Tex.WriteLine(&#8220;Arungg has launced another article&#8221;);<br />
Tex.WriteLine(&#8220;csharpheaven is the new url for c-sharpcorner&#8221;);<br />
Tex.Write(Tex.NewLine);<br />
Tex.close;<br />
Console.WriteLine(&#8221; The Text file named Arungg is created &#8220;);<br />
}<br />
}</p>
<p><span class="smallblack"> If you open the text file the data is entered there.</span></p>
<p><span class="smallblack">READING &#8211; TEXT FILE:</span></p>
<p><span class="smallblack">Now let us see how to read a text file using the StreamReader type.</span></p>
<p><span class="smallblack">Let us see some of the main members of the abstract class TextReader.</span></p>
<p><span class="smallblack">1.Read() &#8212; Reads data from an input stream.<br />
2.ReadLine() &#8212; Reads a line of characters from the current stream and returns the data as a string.<br />
3.ReadToEnd() &#8212; Reads all characters to the end of the TextReader and returns them as one string.</span></p>
<p>&nbsp;</p>
<p><span class="smallblack">public class Readtextfile<br />
{<br />
public static int Main(string[] args)<br />
{<br />
StreamReader re = File.OpenText(&#8220;Arungg.txt&#8221;);<br />
string input = null;<br />
while ((input = re.ReadLine()) != null)<br />
{<br />
Console.WriteLine(input);<br />
}<br />
re.close;<br />
return 0;<br />
}<br />
}<br />
</span></p>
<p><span class="smallblack">In the above class Readtextfile I open the text file Arungg.txt and read the contents using the ReadLine() method.In both StreamReader and StreamWriter are concerned with moving text data to and from a specified file.</span></p>
<p><span class="smallblack">STRINGWRITERS &amp; STRINGREADERS:</span></p>
<p><span class="smallblack">Using the StringReaders and StringWriters cantreat textual information as a stream of in-memory characters. In thiswe can insert or remove string between a block of textual data.Let us see a program in which I add and delete some string between ablock of text.&lt;pre. wr=&#8221;new&#8221;&gt;Running the above program we get the textual data in the console.&lt;/pre.&gt;</span><br />
<br /><i>Continues&#8230;</i></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2006/04/textreader-and-textwriter-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Simple Text File Operations in C#.</title>
		<link>http://www.csharphelp.com/2005/12/simple-text-file-operations-in-c/</link>
		<comments>http://www.csharphelp.com/2005/12/simple-text-file-operations-in-c/#comments</comments>
		<pubDate>Mon, 12 Dec 2005 04:01:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[C# Language]]></category>
		<category><![CDATA[I/O]]></category>

		<guid isPermaLink="false">http://www.csharphelp.com.php5-3.dfw1-2.websitetestlink.com/?p=25</guid>
		<description><![CDATA[C-Sharp provides a File class which is used in manipulating text files. The File class is within the System namespace. Also we can use the StreamReader and StreamWriter classes, which are within the System.IO, namespace for reading from and writing to a text file. In this article we&#8217;ll see examples of Creating a text file, [...]]]></description>
			<content:encoded><![CDATA[<p><span class="smallblack">C-Sharp provides a File class which is used in manipulating text files. The File class is within the System namespace. Also we can use the StreamReader and StreamWriter classes, which are within the System.IO, namespace for reading from and writing to a text file. In this article we&#8217;ll see examples of Creating a text file, reading contents of a text file and appending lines to a text file.</span></p>
<p><strong>1.Creating a Text File</strong></p>
<p><span class="smallblack">For creating text file we use the CreateText Method of the FileClass. The CreateText methods takes in the path of the file to be created as an argument. It creates a file in the specified path and returns a StreamWriter object which can be used to write contents to the file.</span></p>
<p><span style="text-decoration: underline;">Example</span></p>
<p><code><br />
<span class="smallblack">public class FileClass<br />
{<br />
public static void Main()<br />
{<br />
WriteToFile();<br />
}<br />
static void WriteToFile()<br />
{<br />
StreamWriter SW;<br />
SW=File.CreateText("c:\\MyTextFile.txt");<br />
SW.WriteLine("God is greatest of them all");<br />
SW.WriteLine("This is second line");<br />
SW.Close();<br />
Console.WriteLine("File Created SucacessFully");<br />
}<br />
}<br />
</span></code></p>
<p><span class="smallblack"><strong>2.Reading Contents Of A Text File</strong></span></p>
<p><span class="smallblack">For reading the contents of a text file we use the OpenText Method of the File Class.The OpenText methods takes in the path of the file to be opened as an argument. It opens the specified file and returns a StreamReader object which can be used to read the contents of the file.</span></p>
<p><span style="text-decoration: underline;">Example</span></p>
<p><code><br />
<span class="smallblack">public class FileClass<br />
{<br />
public static void Main()<br />
{<br />
ReadFromFile("c:\\MyTextFile.txt");<br />
}<br />
static void ReadFromFile(string filename)<br />
{<br />
StreamReader SR;<br />
string S;<br />
SR=File.OpenText(filename);<br />
S=SR.ReadLine();<br />
while(S!=null)<br />
{<br />
Console.WriteLine(S);<br />
S=SR.ReadLine();<br />
}<br />
SR.Close();<br />
}<br />
}<br />
</span></code></p>
<p><span class="smallblack"><strong>3.Appending Content To A Text File</strong></span></p>
<p><span class="smallblack">For appending content to a text file we use the AppendText Method of the File Class. The AppendText methods takes in the path of the file to which the contents to be appended as an argument. It opens the file in the specified path and returns a StreamWriter object which can be used to append contents to the file.</span><br /><i>Continues&#8230;</i></p>
]]></content:encoded>
			<wfw:commentRss>http://www.csharphelp.com/2005/12/simple-text-file-operations-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

