Den här artikeln visar några alternativ för att skriva text till en fil med C# i ASP.NET Core. Du kanske vill skriva text till en fil för att exportera data, för att felsöka ditt program eller för att mata ut information från ditt program.
Skapa en CSV-fil
En CSV-fil är en textfil där data separeras med kommatecken (,) på varje rad, du kan använda andra tecken för att åtskilja data. En CSV-fil kan importeras i Excel eller Open Office Calc.
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);
}
}
Skapa en XML-fil
Koden nedan visar ett exempel på skapandet av en webbplatskarta i XML-format. Miljörvariabeln (environment) används för att erhålla webbrotsökvägen till applikationen.
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
Skriv till loggfil
Exemplet nedan visar hur du kan lägga till en textrad till en loggfil. Filen skapas automatiskt om den inte existerar. Katalogen (mappen) måste finnas.
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
Skapa en JSON-fil
Du kan serialisera en modell till en JSON-fil. Exemplet nedan visar hur man erhåller programinställningar från en JSON-fil och hur man sparar ändrade inställningar till en JSON-fil.
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