簡體   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