{"id":177,"date":"2012-02-21T21:51:16","date_gmt":"2012-02-21T13:51:16","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=177"},"modified":"2018-09-03T21:33:39","modified_gmt":"2018-09-03T13:33:39","slug":"how-to-write-to-file-in-c","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-write-to-file-in-c\/","title":{"rendered":"How to write to file in C#"},"content":{"rendered":"<p>File output can be used by C# programs to communicate with other programs written in different programming languages, or with human beings. <\/p>\n<p>This post documents my experiences in writing to files in C#.net.  <\/p>\n<h3>Specifying file access<\/h3>\n<p>For file writes, we must use either the <code>Write<\/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 write 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 write to.<\/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-create-a-file-in-c\/\" title=\"How to create a file in C#\" target=\"_blank\">file creation<\/a>, there are a few ways gain code access to a file which we intend to write data:<\/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.Append, FileAccess.Write);\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.Append, FileAccess.Write);\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.Append, \r\n    FileAccess.Write);\r\n<\/pre>\n<\/li>\n<\/ul>\n<p>The above code segments get the operating system to open techcoil.txt for writing to the end of the file. If techcoil.txt does not exist, the operating system will create it.<\/p>\n<h3>Writing text data to file<\/h3>\n<p>To write text data to the file directly, we can encapsulate it in a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.io.streamwriter.aspx\" title=\"MSDN reference for System.IO.StreamWriter\" target=\"_blank\"><code>System.IO.StreamWriter<\/code><\/a> instance and use the <code>Write<\/code> or <code>WriteLine<\/code> method to write text data to the file. The following example writes the current date time to the end of techcoil.txt. <\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nusing System;\r\nusing System.IO;\r\nusing System.Text;\r\n\r\npublic class WriteTextToFile\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        try\r\n        {\r\n            \/\/ If techcoil.txt exists, seek to the end of the file,\r\n            \/\/ else create a new one.\r\n            FileStream fileStream = File.Open(&quot;techcoil.txt&quot;,\r\n                FileMode.Append, FileAccess.Write);\r\n            \/\/ Encapsulate the filestream object in a StreamWriter instance.\r\n            StreamWriter fileWriter = new StreamWriter(fileStream);\r\n            \/\/ Write the current date time to the file\r\n            fileWriter.WriteLine(System.DateTime.Now.ToString());\r\n            fileWriter.Flush();\r\n            fileWriter.Close();\r\n        }\r\n        catch (IOException ioe)\r\n        {\r\n            Console.WriteLine(ioe);\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<h3>Writing binary data to file<\/h3>\n<p>To write binary data to file, we can use the <code>Write<\/code> method of the <code>FileStream<\/code> instance. As with the previous example, the following code writes the current date time string to the end of techcoil.txt. However, it converts the current date time string as bytes before writing to techcoil.txt.<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\npublic class WriteBinaryToFile\r\n{\r\n    public static void Main(string&#x5B;] args)\r\n    {\r\n        try\r\n        {\r\n            \/\/ If techcoil.txt exists, seek to the end of the file,\r\n            \/\/ else create a new one.\r\n            FileInfo fileInfo = new FileInfo(&quot;techcoil.txt&quot;);\r\n            FileStream fileStream = fileInfo.Open(FileMode.Append,\r\n                FileAccess.Write);\r\n\r\n            \/\/ Get the current date time as a string and add a new line to\r\n            \/\/ the end of the string\r\n            String currentDateTimeString = System.DateTime.Now.ToString() \r\n                + Environment.NewLine;\r\n                \r\n            \/\/ Get the current date time string as bytes\r\n            byte&#x5B;] currentDateTimeStringInBytes \r\n                = ASCIIEncoding.UTF8.GetBytes(currentDateTimeString);\r\n                \r\n            \/\/ Write those bytes to the techcoil.txt\r\n            fileStream.Write(currentDateTimeStringInBytes, \r\n                0, currentDateTimeStringInBytes.Length);\r\n            fileStream.Flush();\r\n            fileStream.Close();\r\n        }\r\n        catch (IOException ioe)\r\n        {\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 WriteBinaryToFile\r\n<\/pre>\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 a file in C#<\/a><\/li>\n<li><a href=\"http:\/\/www.techcoil.com\/blog\/quick-references\/how-to-read-from-file-in-c\/\" title=\"How to read from file in C#\" target=\"_blank\">How to read from 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#\">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-2R\" 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-2R&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-2R&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%2F177&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>File output can be used by C# programs to communicate with other programs written in different programming languages, or with human beings. <\/p>\n<p>This post documents my experiences in writing to files in C#.net.  <\/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,94],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/C-Sharp-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-2R","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/177"}],"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=177"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/177\/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=177"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=177"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=177"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}