{"id":174,"date":"2012-02-22T22:00:19","date_gmt":"2012-02-22T14:00:19","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=174"},"modified":"2018-09-03T21:34:01","modified_gmt":"2018-09-03T13:34:01","slug":"how-to-read-from-file-in-c","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-read-from-file-in-c\/","title":{"rendered":"How to read from file in C#"},"content":{"rendered":"<p>The ability to read from file gives our C# programs the ability to act on data given by other programs, which may be written in different programming languages. <\/p>\n<p>Such a ability is also helpful in allowing humans to configure how our C# program will behave at runtime.<\/p>\n<p>Since being able to read from file is so helpful in C#, I want to remember how I can do that with this post.<\/p>\n<h3>Specifying file access<\/h3>\n<p>For file reads, we must use either the <code>Read<\/code> or the <code>ReadWrite<\/code> member of the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/4z36sx0f.aspx\" title=\"MSDN reference for System.IO.FileAccess enumeration\" target=\"_blank\"><code>System.IO.FileAccess<\/code><\/a> enumeration to specify read access.<\/p>\n<h3>Specifying file mode<\/h3>\n<p>Apart from specifying file access, we specify the file mode via one of the members of the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filemode.aspx\" title=\"MSDN reference for System.IO.FileMode enumeration\" target=\"_blank\"><code>System.IO.FileMode<\/code><\/a> enumeration. The file mode determines how the operating system will open the file for our code to read from.<\/p>\n<h3>Getting an instance of System.IO.FileStream<\/h3>\n<p>As with <a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-write-to-file-in-c\/\" title=\"How to write to file in C#\" target=\"_blank\">writing to file<\/a>, there are a few ways which we can get code access to the file that we want to read from. <\/p>\n<ul>\n<li>\nUsing the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.filestream.aspx\" title=\"MSDN reference for System.IO.FileStream\" target=\"_blank\"><code>System.IO.FileStream<\/code><\/a> constructors.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nFileStream fileStream = new FileStream(&quot;techcoil.txt&quot;, \r\n    FileMode.Open, FileAccess.Read);\r\n<\/pre>\n<\/li>\n<li>\nUsing the static <code>Open<\/code> method of <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.file.aspx\" title=\"MSDN reference System.IO.File\" target=\"_blank\"><code>System.IO.File<\/code><\/a> class.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nFileStream fileStream = File.open(&quot;techcoil.txt&quot;, \r\n    FileMode.Open, FileAccess.Read);\r\n<\/pre>\n<\/li>\n<li>\nUsing the <code>Open<\/code> method of the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.fileinfo.aspx\" title=\"MSDN reference for System.IO.FileInfo\" target=\"_blank\"><code>System.IO.FileInfo<\/code><\/a> class.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nFileInfo fileInfo = new FileInfo(&quot;techcoil.txt&quot;);\r\nFileStream fileStream = fileInfo.Open(FileMode.Open, \r\n    FileAccess.Read);\r\n<\/pre>\n<\/li>\n<\/ul>\n<p>The above code segments attempt to open techcoil.txt. If techcoil.txt does not exists, an instance of <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.ioexception.aspx\" title=\"MSDN reference for System.IO.IOException\" target=\"_blank\">System.IO.IOException<\/a> will be thrown. <\/p>\n<p>Personally, I prefer using the last method as the <code>FileInfo<\/code> instance can provide me with useful information about the file. For instance, I can check whether the file exists before I attempt to gain code access to the file:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nFileInfo fileInfo = new FileInfo(&quot;techcoil.txt&quot;);\r\n\/\/ Check whether techcoil.txt exists                \r\nif (fileInfo.Exists)\r\n{\r\n    FileStream fileStream = fileInfo.Open(FileMode.Open,\r\n        FileAccess.Read);\r\n    \/\/ Use fileStream to read data from file...\r\n} \r\nelse \r\n{\r\n    Console.WriteLine(&quot;techcoil.txt does not exists.&quot;);\r\n}\r\n<\/pre>\n<h3 id=\"readTextFromFile\">Reading text from file<\/h3>\n<p>Assuming that we want to read text from techcoil.txt and output the contents to console. The following code segment demonstrates how we can do this.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class ReadTextFromFile\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        try\r\n        {\r\n            FileInfo fileInfo = new FileInfo(&quot;techcoil.txt&quot;);\r\n            \/\/ If techcoil.txt exists \r\n            if (fileInfo.Exists)\r\n            {\r\n                \/\/ Get an instance of FileStream that represents\r\n                \/\/ techcoil.txt\r\n                FileStream fileStream = fileInfo.Open(FileMode.Open,\r\n                    FileAccess.Read);\r\n                \/\/ Encapsulate the file stream instance in a StreamReader\r\n                \/\/ instance\r\n                StreamReader reader = new StreamReader(fileStream);\r\n                String line;\r\n\r\n                \/\/ Read the file, line by line\r\n                while ((line = reader.ReadLine()) != null)\r\n                {\r\n                    \/\/ Print out the line to console\r\n                    Console.WriteLine(line);\r\n                } \/\/ end while\r\n                \r\n                reader.Close();\r\n            }\r\n            else\r\n            {\r\n                Console.WriteLine(&quot;techcoil.txt does not exist.&quot;);\r\n            } \/\/ end if\r\n        }\r\n        catch (IOException ioe) {\r\n            Console.WriteLine(ioe);\r\n        } \/\/ end try-catch\r\n\r\n    } \/\/ end public static void Main(string&#x5B;] args)\r\n} \/\/ end class public class ReadTextFromFile\r\n<\/pre>\n<p>The code segment starts by checking whether techcoil.txt exists. If it exists, an instance of the <code>FileStream<\/code> class is created via the <code>FileInfo<\/code> instance. The <code>FileStream<\/code> instance is then encapsulated in a <code>System.IO.StreamReader<\/code> instance, which is capable of reading text. <\/p>\n<p>When the code is able to get read access to the file, the while loop reads the contents of the file and output to the console, line by line. When there are no more lines to read, <code>reader.ReadLine<\/code> returns null.<\/p>\n<h3>Reading binary data from file<\/h3>\n<p>We can use the <code>Read<\/code> method from the <code>FileStream<\/code> instance to read binary data from the file. Let's demonstrate this through a file copy example. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class ReadBinaryDataFromFile\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        try\r\n        {\r\n            FileInfo fileInfo = new FileInfo(&quot;techcoil.txt&quot;);\r\n                \r\n            if (fileInfo.Exists)\r\n            {\r\n                byte&#x5B;] buffer = new byte&#x5B;1024];\r\n\r\n                \/\/ Get read access to file to copy from\r\n                FileStream srcFileStream = new FileStream(&quot;techcoil.txt&quot;, \r\n                    FileMode.Open, FileAccess.Read);\r\n                \r\n                \/\/ Get write access to new file to copy to\r\n                FileStream destFileStream = new FileStream(&quot;techcoil_new.txt&quot;, \r\n                    FileMode.Create, FileAccess.Write);\r\n\r\n                int bytesRead;\r\n                while((bytesRead = srcFileStream.Read(buffer, 0, buffer.Length)) != 0) {\r\n                    Console.WriteLine(&quot;File copying in progress&quot;);\r\n                    \/\/ Write the bytes read to new file\r\n                    destFileStream.Write(buffer, 0, bytesRead);\r\n                } \/\/ end while\r\n\r\n                srcFileStream.Close();\r\n                destFileStream .Close();\r\n            }\r\n            else\r\n            {\r\n                Console.WriteLine(&quot;techcoil.txt does not exist&quot;);\r\n            } \/\/ end if\r\n        }\r\n        catch (IOException ioe) {\r\n            Console.WriteLine(ioe);\r\n        } \/\/ end try-catch\r\n    } \/\/ end public static void Main(string&#x5B;] args)\r\n} \/\/ end public class ReadBinaryDataFromFile\r\n<\/pre>\n<p>The code segment starts by checking the existence of techcoil.txt - the source file to copy data from. If techcoil.txt exists, a 1024-sized byte array is set aside to hold data during file reads. Two <code>FileStream<\/code> instances are then created, one having <strong>read<\/strong> access to techcoil.txt; the other having <code>write<\/code> access to techcoil_new.txt - the destination file to copy data to. When both the files can be accessed for reading and writing, the program proceeds on with copying data from techcoil.txt to techcoil_new.txt.<\/p>\n<p>In the while loop, <code>srcFileStream.Read<\/code> populates <code>buffer<\/code> with data, starting from the first element position (at index 0) to the last element position, <strong>where possible<\/strong>. It returns the number of bytes copied to buffer. <\/p>\n<h3>Some reflects about this post<\/h3>\n<h4>Why do we use <code>Console.WriteLine<\/code> instead of <code>Console.Write<\/code> to output the content read by <code>reader.ReadLine<\/code>?<\/h4>\n<p>The <code>ReadLine<\/code> method will remove the new line character that denotes the end of line. By using <code>Console.WriteLine<\/code>, we put back the new line character onto the console screen. <\/p>\n<h4>Instead of getting a <code>FileStream<\/code> instance, can we get a <code>StreamReader<\/code> instance directly?<\/h4>\n<p>Yes, there are a couple of ways to get a <code>StreamReader<\/code> instance directly.<\/p>\n<ul>\n<li> Use the <code>OpenText()<\/code> method of the <code>fileInfo<\/code> instance.\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nFileInfo fileInfo = new FileInfo(&quot;techcoil.txt&quot;);\r\nStreamReader reader = fileInfo.OpenText();\r\n<\/pre>\n<\/li>\n<li>Use the static <code>OpenText()<\/code> method of the <code>File<\/code> class.\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nStreamReader reader = File.OpenText(&quot;techcoil.txt&quot;);\r\n<\/pre>\n<\/li>\n<li>\nUse the <code>StreamReader<\/code> constructor<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nStreamReader reader = new StreamReader(&quot;techcoil.txt&quot;);\r\n<\/pre>\n<\/li>\n<\/ul>\n<h4>Instead of manually doing binary data file copy, is there a shorter way to perform file copy?<\/h4>\n<p>Yes, we can use the System.IO.File.Copy method to perform the file copy:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nFile.Copy(&quot;techcoil.txt&quot;, &quot;techcoil_new.txt&quot;, true);\r\n<\/pre>\n<p>The above code segment will copy the contents of techcoil.txt to techcoil_new.txt. A true value given as the third parameter indicates that if techcoil_new.txt exists, it's content will be overridden. <\/p>\n<h4>Why do we bother with manually copying the binary data file when there is a fast and easy way of doing so?<\/h4>\n<p>One reason for doing so is when it is necessary to provide feedback to the file copying progress to user, especially when copying very large file. Another situation that I could recall was trying to send a <a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/uploading-large-http-multipart-request-with-system-net-httpwebrequest-in-c\/\" title=\"Uploading large HTTP multipart request with System.Net.HttpWebRequest in C#\" target=\"_blank\">large multipart HTTP request<\/a> to a server endpoint. By performing the binary read directly, I can show my user how many bytes had been read from file and how many bytes had been sent to the <a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/a-mechanism-for-serving-http-requests-in-c\/\" title=\"A mechanism for serving HTTP requests in C#\" target=\"_blank\">HTTP server<\/a> endpoint. <\/p>\n<h3>Related posts<\/h3>\n<ul>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-create-a-file-in-c\/\" title=\"How to create a file in C#\">How to create file in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-write-to-file-in-c\/\" title=\"How to write to file in C#\" target=\"_blank\">How to write to file in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-save-and-load-objects-to-and-from-file-in-c\/\" title=\"How to save and load objects to and from file in C#\" target=\"_blank\">How to save and load objects to and from file in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/c-facilities-for-dealing-with-folders\/\" title=\"C# facilities for dealing with folders\" target=\"_blank\">C# facilities for dealing with folders<\/a><\/li>\n<\/ul>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-2O\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-2O&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-2O&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F174&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>The ability to read from file gives our C# programs the ability to act on data given by other programs, which may be written in different programming languages. <\/p>\n<p>Such a ability is also helpful in allowing humans to configure how our C# program will behave at runtime.<\/p>\n<p>Since being able to read from file is so helpful in C#, I want to remember how I can do that with this post.<\/p>\n","protected":false},"author":1,"featured_media":1189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[20,95,85,86,87,96],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/C-Sharp-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-2O","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/174"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=174"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/174\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1189"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=174"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=174"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=174"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}