Reputation: 42957
I am writing a method that take a string containing a message and write this string into a log file.
I have done in this way:
internal static void WriteLogFile(string messageLog)
{
if (messageLog == "")
{
messageLog = "L'import delle regole di inoltro è andato a buon fine. Tutte le regole di inoltro sono state inserite";
}
try
{
var filePath = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
CultureInfo ci = new CultureInfo("it-IT");
File.WriteAllText(filePath + "log.txt", messageLog);
Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
}
catch (Exception ex)
{
throw ex;
}
}
The problem is that when perform this line:
File.WriteAllText(filePath + "log.txt", messageLog);
I am obtaining the following exception:
"URI formats are not supported."
What is wrong? What am I missing? How can I try to fix it?
Upvotes: 1
Views: 218
Reputation: 498
Because WriteAllText does not support a URI format, and you're using a URI.
Per https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.8, you need to pass it a string path.
As others have suggested, you should use GetPath if you want to create the file locally, or some other method depending where you want the file to go.
Upvotes: 1
Reputation: 57946
I'm assuming your problem is to write a log file in the same folder as your executable. Try to use the Location
property:
var filePath = Assembly.GetEntryAssembly().Location;
That will return a valid path that you can concatenate with the file name, or use Path.Combine
method.
Upvotes: 1
Reputation: 5203
Try this class:
using System;
using System.IO;
namespace YourNameSpace.Models
{
public class Logger
{
private Object Locker { get; set; }
public string Path { get; set; }
public Logger(string path)
{
Locker = new Object();
Path = path;
}
public void Log(string message, params object[] args)
{
lock (Locker)
{
string messageToLog = string.Format("{0} - {1}", DateTime.Now, string.Format(message, args));
string path = System.IO.Path.Combine(Path, string.Format("{0}.txt", DateTime.Today.ToString("yyyyMMdd")));
Directory.CreateDirectory(Path);
File.AppendAllLines(path, new string[] { messageToLog });
}
}
}
}
Upvotes: 1