Writing Data into a File on Hololens

2019-07-24 21:38发布

问题:

in my Hololens app i want to write data into a file which i can then view over the Device Portal. The Data contains just the time from one airtap on a special object to another airtap. The problem ist that there will be no file created in the Device Portal under /LocalAppData/YourApp/LocalState

Thanks in advance

Jonathan

public void StopTime()

{

    TimeSpan ts = time.Elapsed;
    time.Stop();
    path = Path.Combine(Application.persistentDataPath, "Messdaten.txt");
    using (TextWriter writer = File.CreateText(path))
    {
        writer.Write(ts);
    }
}

回答1:

I usually use a FileStream and a StreamWriter and make sure the FileMode.Create is set.

See also How to write text to a file for more approaches

using (var file = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write))
{
    using (var writer = new StreamWriter(file, Encoding.UTF8))
    {
        writer.Write(content);
    }
}

With that I never had any trouble on the HoloLens so far.

You also might want to use something like ts.ToString() in order to format the value to your needs.


Alternatively you could also try Unity's Windows.File (only available for UWP) but than you need to have byte[] as input. E.g. from here

long c = ts.Ticks;
byte[] d = BitConverter.GetBytes(c);

File.WriteAllBytes(path, d);


回答2:

The simplest thing to do is to use File.WriteAllText method https://docs.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.7.2

Obviously there are many ways that could work but it is good to stick to the simplest solution.