Monday, August 26, 2019

Create a new text file and write or append text to the file using C#


Each time the C# code block is called it creates a file with file name built from current system date. If it is call multiple times it creates the file at first call and in subsequent calls it appends the texts to the files existing content. When date changes, it creates a new file on first call and then appends text.

            string date = DateTime.Now.ToString("yyyy-MM-dd");
            string filename = date + ".txt";
            string file = HttpContext.Current.Server.MapPath("~/App_Data/" + filename);
            bool exists = File.Exists(file);
            if (!exists)
            {
                FileStream fs = File.Create(file);
                fs.Close();
            }

          using (StreamWriter writer = File.AppendText(file))
            {
                writer.WriteLine("=========Text Block=========");
                writer.WriteLine("Date Time: " + DateTime.Now.ToString());
                writer.WriteLine("This is repeating text for testing");
                writer.Close();
            }



No comments:

Post a Comment

Please keep your comments relevant.
Comments with external links and adult words will be filtered.