c# - 使用 StreamWriter 的文件中的 NULL 符号

标签 c# android ios unity3d stream

我想在我的应用程序中添加简单的记录器。
为此,我想使用 StreamWriter .

代码:

private StreamWriter OutputStream;
OutputStream = new StreamWriter(this.LogFilePath, true);

// .... message - log from app

DateTime now = DateTime.Now;
message = string.Format("[{0:yyyy-MM-dd H:mm:ss}] {1}", now, message
if (OutputStream != null)
{
    OutputStream.WriteLine(message);
    OutputStream.Flush();
}

结果所有字符串都被正确捕获并且输出正确,但有时它可以在末尾写入带有不可见字符的空字符串:

样本:

 [1970-08-31 14:56:26] Command response -> !c:65:f9:1b:82:97


如果我检查这个 with some tool that can show invisible characters ,我可以看到下一个:

enter image description here

结果 ~600 行日志 - 125 mb。

我有 found这个原因可能是下一个:

That happens. When you append a file first its size is corrected in the directory (and that's transactional in NTFS) and then the actual new data is written. There's good chance that if you shut down the system you end up with a file appended with lots of null bytes because data writes are not transactional unlike metadata (file size) writes.

There's no absolute solution to this problem.



也尝试过

使用 isControl 检查字符其他类似检查;

试图 Trim最后一个字符;

已检查 docs - 看起来都正确

有什么建议吗?

最佳答案

万一有人遇到同样的问题-我的原因未知,我可能只能猜测....但是我用日志系统重写逻辑并且错误消失了:

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;

public class EventLogger : MonoBehaviour
{
    private string logFileName = "btlog.txt";
    public bool EchoToConsole = true;
    public bool AddTimeStamp = true;
    public bool EnableFileStorage = true;

    private string LogFilePath
    {
        get
        {
            return Path.Combine(Application.persistentDataPath, logFileName);
        }
    }

    private static EventLogger Singleton = null;
    const string format = "yyyy-MM-dd HH:mm:ss.fffffff";

    public static EventLogger Instance
    {
        get { return Singleton; }
    }

    void Awake()
    {
        if (Singleton != null)
        {
            UnityEngine.Debug.LogError("Multiple EventLogger Singletons exist!");
            return;
        }

        Singleton = this;

        if (this.EnableFileStorage)
        {
            if (File.Exists(LogFilePath))
            {
                long length = new FileInfo(LogFilePath).Length;
                int limit = 1024 * 1024 * 5; // 5mb
                if (length > limit)
                {
                    File.Delete(LogFilePath);
                    Log("log file removed");
                }
            }

            Log("-------------------");
            Log("NEW SESSION STARTED");
        }
    }

    private async Task Write(string message)
    {
        if (this.EnableFileStorage)
        {
            if (AddTimeStamp)
            {
                DateTime now = DateTime.Now;

                string strDate = now.ToString(format);
                string trimmed = new string(message.Where(c => !char.IsControl(c)).ToArray());
                message = string.Format("[{0}] {1}", strDate, trimmed);
            }

            using (StreamWriter outputStream = new StreamWriter(this.LogFilePath, true))
            {
                await outputStream.WriteLineAsync(message);
            }

            if (EchoToConsole)
            {
                UnityEngine.Debug.Log(message);
            }
        }
    }

    [Conditional("DEBUG"), Conditional("PROFILE")]
    public static void Log(string Message)
    {
        if (EventLogger.Instance != null)
        {
            _ = EventLogger.Instance.Write(Message);
        }
        else
        {
            UnityEngine.Debug.Log(Message);
        }
    }
}

关于c# - 使用 StreamWriter 的文件中的 NULL 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61359119/

相关文章:

java - 在 Java httpclient 中设置用户代理并允许重定向到 true

ios - MKMapView中如何区分用户拖动 map 和位置变化?

ios - 强制模拟位置在 XCode 6.4 中固定

c# - Xamarin Forms - 如何在 POST 方法响应中获取 json 字符串?

c# - Web 服务 asmx 不适用于单声道 4.2.3.4 Debian 8.2

c# - 在 C# 问题中填充 selectList

android - picasso 在纵向和横向模式下加载不同的图像

java - Android中动态添加onClick ActionListener到CheckBox

c# - 什么停止(而不是崩溃)我的 Windows 服务?

ios - openURL 在 Action Extension 中不起作用