Skip to content

Write text to file in ASP.NET Core

This article shows some alternatives to write text to a file with C# in ASP.NET Core. You may want to write text to a file to export data, to debug your program or to output information from your program.

Create a CSV file

A CSV file is a text file where the data is separated by comma (,) on each row, you can use other characters to separate data. A CSV file can be imported in Excel or in Open Office Calc for example.

using (StreamWriter writer = new StreamWriter("D:\\MyFolder\\TEST\\Files\\case.txt"))
{
    for (int i = 0; i < input.Length; i++)
    {
        writer.WriteLine(input[i].text + "," + input[i].powerofbase
            + "," + input[i].int_value.ToString(CultureInfo.InvariantCulture)
            + "," + input[i].decimal_value.ToString(CultureInfo.InvariantCulture)
            + "," + input[i].last_numbers.ToString(CultureInfo.InvariantCulture)
            + "," + input[i].index);
    }
}

Create an XML file

The code below shows an example of the creation of a sitemap in XML-format. The environment variable is used to get the web root path of the application.

public class SitemapRepository : ISitemapRepository
{
    #region Variables

    private readonly IWebHostEnvironment environment;
    private readonly IStaticPageRepository static_page_repository;
    private readonly IGroupRepository group_repository;

    #endregion

    #region Constructors

    public SitemapRepository(IWebHostEnvironment environment, IStaticPageRepository static_page_repository, IGroupRepository group_repository)
    {
        // Set values for instance variables
        this.environment = environment;
        this.static_page_repository = static_page_repository;
        this.group_repository = group_repository;

    } // End of the constructor

    #endregion

    #region Methods

    public void CreateSitemap()
    {
        // Create the directory path
        string directoryPath = this.environment.WebRootPath + "\\sitemaps\\";

        // Check if the directory exists
        if (System.IO.Directory.Exists(directoryPath) == false)
        {
            // Create the directory
            System.IO.Directory.CreateDirectory(directoryPath);
        }

        // Create the file
        string filepath = directoryPath + "Sitemap.xml.gz";

        // Get static pages and groups
        IList<StaticPage> staticPages = this.static_page_repository.GetAllActiveLinks("title", "ASC");
        IList<Group> groups = this.group_repository.GetAll("title", "ASC");

        // Create variables
        GZipStream gzipStream = null;
        XmlWriter xmlTextWriter = null;

        try
        {
            // Create a gzip stream
            gzipStream = new GZipStream(new FileStream(filepath, FileMode.Create), CompressionMode.Compress);

            // Create a xml text writer
            XmlWriterSettings xwSettings = new XmlWriterSettings
            {
                Encoding = new UTF8Encoding(true)
            };
            xmlTextWriter = XmlWriter.Create(gzipStream, xwSettings);

            // Write the start of the document
            xmlTextWriter.WriteStartDocument();

            // Write the url set for the xml document <urlset>
            xmlTextWriter.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
            xmlTextWriter.WriteAttributeString("xmlns", "image", null, "http://www.google.com/schemas/sitemap-image/1.1");
            xmlTextWriter.WriteAttributeString("xmlns", "video", null, "http://www.google.com/schemas/sitemap-video/1.1");

            // Create the start string
            string baseUrl = "https://www.mysite.se";

            // Add the baseurl
            CreateUrlPost(xmlTextWriter, baseUrl, "1.0", "monthly", DateTime.UtcNow);

            // Loop static pages
            for (int i = 0; i < staticPages.Count; i++)
            {
                // Create the url post
                if (staticPages[i].meta_robots.StartsWith("index") == true)
                {
                    CreateUrlPost(xmlTextWriter, baseUrl + "/home/page/" + staticPages[i].page_name, "0.9", "monthly", DateTime.UtcNow);
                } 
            }

            // Loop groups
            for (int i = 0; i < groups.Count; i++)
            {
                // Create the url post
                if(groups[i].meta_robots.StartsWith("index") == true)
                {
                    CreateUrlPost(xmlTextWriter, baseUrl + "/home/group/" + groups[i].page_name, "0.2", "monthly", DateTime.UtcNow);
                }
            }

            // Write the end tag for the xml document </urlset>
            xmlTextWriter.WriteEndDocument();

            // Flush the writer
            xmlTextWriter.Flush();
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            // Close streams
            if (xmlTextWriter != null)
            {
                // Close the XmlTextWriter
                xmlTextWriter.Dispose();
            }
            if (gzipStream != null)
            {
                // Close the gzip stream
                gzipStream.Dispose();
            }
        }

    } // End of the CreateSitemap method

    private void CreateUrlPost(XmlWriter xmlTextWriter, string url, string priority, string changeFrequency, DateTime lastModifiedDate)
    {
        xmlTextWriter.WriteStartElement("url");
        xmlTextWriter.WriteStartElement("loc");
        xmlTextWriter.WriteString(url);
        xmlTextWriter.WriteEndElement();
        xmlTextWriter.WriteStartElement("lastmod");
        xmlTextWriter.WriteString(string.Format("{0:yyyy-MM-dd}", lastModifiedDate));
        xmlTextWriter.WriteEndElement();
        xmlTextWriter.WriteStartElement("changefreq");
        xmlTextWriter.WriteString(changeFrequency);
        xmlTextWriter.WriteEndElement();
        xmlTextWriter.WriteStartElement("priority");
        xmlTextWriter.WriteString(priority);
        xmlTextWriter.WriteEndElement();
        xmlTextWriter.WriteEndElement();

    } // End of the CreateUrlPost method

    #endregion

} // End of the class

Write to log-file

The example below shows how you can append a line of text to a log file. The file is created automatically if does not exist. The directory must exist.

private void LogError(string error)
{
    // Set the file path
    string path = this.directory + "\\errors.txt";

    // Add the error message to the file
    System.IO.File.AppendAllText(path, $"{DateTime.Now.ToString("o")} [ERR] {error}" + Environment.NewLine);

} // End of the LogError method

Create a JSON file

You can serialize a model to a JSON file. The example below shows how to get applications settings from a JSON file and how to save modified settings to a JSON file.

string path = this.directory + "\\appsettings.json";

// Get the data
string data = System.IO.File.ReadAllText(path, Encoding.UTF8);

// Convert data to app settings
AppSettings app_settings = JsonConvert.DeserializeObject<AppSettings>(data);

// Modify application settings

// Write updated application settings to the file
System.IO.File.WriteAllText(path, JsonConvert.SerializeObject(app_settings, Formatting.Indented));
public class AppSettings
{
    #region Variables

    public Logging Logging { get; set; }
    public DoxservrOptions DoxservrOptions { get; set; }
    public FortnoxOptions FortnoxOptions { get; set; }
    public DefaultValues DefaultValues { get; set; }

    #endregion

    #region Constructors

    public AppSettings()
    {
        // Set values for instance variables
        this.Logging = new Logging();
        this.DoxservrOptions = new DoxservrOptions();
        this.FortnoxOptions = new FortnoxOptions();
        this.DefaultValues = new DefaultValues();

    } // End of the constructor

    #endregion

} // End of the class

Leave a Reply

Your email address will not be published. Required fields are marked *