为什么在尝试使用C#写入日志文件时出现“不支持URI格式”异常?

时间:2019-05-20 12:48:36

标签: c# .net

我正在编写一种方法,该方法采用包含消息的字符串并将此字符串写入日志文件。

我以这种方式完成了

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;
    }
}

问题是执行此行时:

File.WriteAllText(filePath + "log.txt", messageLog);

我收到以下异常:

"URI formats are not supported."

怎么了?我想念什么?我该如何解决?

3 个答案:

答案 0 :(得分:1)

尝试这个课程:

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 });
            }
        }
    }
}

答案 1 :(得分:1)

我假设您的问题是在与可执行文件相同的文件夹中写入日志文件。尝试使用Location属性:

var filePath = Assembly.GetEntryAssembly().Location;

这将返回一个可以与文件名连接的有效路径,或使用Path.Combine方法。

答案 2 :(得分:1)

因为WriteAllText不支持URI格式,而您正在使用URI。

对于每个https://docs.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.8,您需要向其传递一个字符串路径。

正如其他人所建议的那样,如果要在本地创建文件,则应使用GetPath,或根据文件要移至的位置使用其他方法。