繁体   English   中英

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

[英]Why am I obtaining “URI formats are not supported” exception trying to write into a log file using C#?

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

我这样做了:

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."

怎么了? 我错过了什么? 我该如何解决这个问题?

试试这堂课:

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

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

var filePath = Assembly.GetEntryAssembly().Location;

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM