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);
}
}
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);
The simplest thing to do is to use File.WriteAllText method https://learn.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.
Related
Here is my code. :
FileStream fileStreamRead = new FileStream(pathAndFileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
FileStream fileStreamWrite = new FileStream(reProcessedFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
StreamWriter sw = new StreamWriter(fileStreamWrite);
int readIndex = 0;
using (StreamReader sr = new StreamReader(fileStreamRead))
{
while (!sr.EndOfStream) {
Console.WriteLine("eof" + sr.EndOfStream);
readIndex++;
Console.WriteLine(readIndex);
string currentRecord = "";
currentRecord = sr.ReadLine();
if (currentRecord.Trim() != "")
{
Console.WriteLine("Writing " + readIndex);
sw.WriteLine(currentRecord);
}
else {
Console.WriteLine("*******************************************spaces ***********************");
}
}
It is cutting off 2 lines with one test file and half a line, and then 1 line and half a line with the other test file I am running it against.
I am not a streamreader/writer expert you can probably see.
Any ideas or suggestions would be greatly appreciated as this is driving me batty. I am sure it is me using these incorrectly.
You are missing Flush/Close or simply using for your writer.
using(FileStream fileStreamWrite =
new FileStream(reProcessedFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
{
using(StreamWriter sw = new StreamWriter(fileStreamWrite))
{
// .... write everything here
}
}
Right after the closing brace of the using statement, do this:
sw.Flush();
sw.Close();
There, that should do it.
You need to Flush your StreamWriter. A StreamWriter has a buffer, and it writes to disk only when the buffer is full. By flushing at the end you make sure all the text in the buffer is written to the disk.
In addition to other answers (use using, and/or flush/close), would say that they do not actually respond to the question: "why it may cut several lines."
I have an idea on subject that it is related to a fact that you use StreamReader and call EndOfStream twice: in a while loop header, and another inside it.
The only possible way of understanding if the stream ends is try to read some data from it. So I suspect EnfOfStream does it, and reading it twice, may create a problem in stream processing.
To resolve an issue:
Or use simple TextReader, considering that you are reading text file (seems to me)
Or change your logic to call only once, so no more call to Console.WriteLine("eof" + sr.EndOfStream);
Or change your logic, so do not use EndOFStream at all, but read line by line till the line is null.
You're not using StreamWriter properly. Also, since you're always reading lines, I would use a method that already does all that for you (and manages it properly).
using (var writer = new StreamWriter("path"))
{
foreach(var line in File.ReadLines("path"))
{
if (string.IsNullOrWhiteSpace(line))
{ /**/ }
else
{ /**/ }
}
}
... or ...
/* do not call .ToArray or something that will evaluate this _here_, let WriteAllLines do that */
var lines = File.ReadLines("path")
.Select(line => string.IsNullOrWhiteSpace(line) ? Stars : line);
var encoding = Encoding.ASCII; // whatever is appropriate for you.
File.WriteAllLines("path", lines, encoding);
I am trying to unit test a method that calls StreamWriter. I am trying to use System.IO.Abstraction in order to mock StreamWriter however I can't find the interface on the last NuGet looked into the source code as well but have no idea what is the replacement for this, other stuff like FileInfo is working as expected.
Thanks,
Taking #BarryMcDermid's answer and altering it slightly you can do something along the lines of:
using (Stream fs = _fileSystem.FileStream.Create(filePath, FileMode.Create))
{
ms.CopyTo(fs);
fs.Flush();
fs.Close();
}
By declaring the 'FileStream' as a Stream instead of a FileStream you'll then be able to use System.IO.Abstraction.TestingHelpers to test this code without getting exceptions.
There's a more fully worked example of that in my question here.
I was also looking for how to mock a FileStream via System.IO.Abstractions and couldn't see it initially. It's Hanging off the FileInfo Object. It results in slightly clunky code and required a cast. My Original Code:
FileStream fileStreamBack = null;
using (fileStreamBack = new FileStream(fileFrom, FileMode.Open, FileAccess.Read))
using (var fileStreamf = new FileStream(fileTo, FileMode.Create, FileAccess.Write))
{
fileStreamBack.CopyTo(fileStreamf); // Use the .Net
fileStreamBack.Flush(); // Making sure
fileStreamBack.Close(); // Making sure
}
Now Replaced with
FileStream fileStreamBack = null;
using (fileStreamBack = (FileStream)_fileSystem.FileInfo.FromFileName(fileFrom).Open(FileMode.Open, FileAccess.Read))
using (var fileStreamf = (FileStream)_fileSystem.FileInfo.FromFileName(fileTo).Open(FileMode.Create, FileAccess.Write))
{
fileStreamBack.CopyTo(fileStreamf); // Use the .Net
fileStreamBack.Flush(); // Making sure
fileStreamBack.Close(); // Making sure
}
There is also a MockFileStream object in the System.IO.Abstractions.TestingHelpers (for our convenience!)
i have problems during parsing request files.
my file size is 1338521 bytes, but Nancy says, that file size is some times 1751049 or 3200349.
on my windows pc it works fine, on linux server this problem appears, so i can't save file.
string result = Convert.ToBase64String(Core.ReadBytesFromStream(file.Value));
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(result)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save(path);
}
}
any ideas?
You don't need to convert the file like that.
var filename = Path.Combine(storagePath, Request.Files[0].Name);
using (var fileStream = new FileStream(filename, FileMode.Create))
{
Request.Files[0].Value.CopyTo(fileStream);
}
Validate the file when it comes in to ensure the extension is accepted, create a save path, and copy the stream to a new file on the filesystem.
That's it.
I'm using the FileHelpers library for a C# .net project. All is working ok except I need to have the generated CSV savable via a button click.
So the user clicks a button and they get a prompt to save the file. I know Filehelpers has a WriteStream option but their own documentation shows only an example of WriteFile. I don't know if WriteStream is what's needed but I think it is.
Anyone know if it's possible to have the CSV file saved directly to the client rather than to the server hard drive?
Thanks.
UPDATE WITH MORE DETAIL:
I'll try to give more detail to help clarify what it is I'm trying to achieve. I don't want to save any file on the server. I am using FileHelpers to generate a record and I want to try and use their WriteStream method to write that record as a CSV directly to their browser; but the example they provide doesn't actually use that method at all, strangely.
Here's the link to their method:
http://www.filehelpers.com/FileHelpers.FileHelperEngine.WriteStream_overload_2.html
And here's the method in question.
public void WriteStream(
TextWriter writer,
IEnumerable records,
int maxRecords
);
I can easily save the file to the server but don't want to as I've no need for it and want to get the client to save it directly to their own machine.
It may be that I have to go through the normal route to achieve this but I saw the WriteStream method and thought maybe FileHelpers facilitated a nice clean way of achieving the same result.
Hope this is clearer.
You should be able to do something like the following:
Response.ContentType = #"application/x-msdownload";
Response.AppendHeader("content-disposition", "attachment; filename=" + FILE_NAME);
Response.Write(csv.ToString());
Response.Flush();
Response.End();
There are plenty of more elaborate suggestions on StackOverflow such as this one. It depends what you are trying to achieve.
EDIT
I think the steps you are missing are:
MemoryStream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(stream);
engine.WriteStream(streamWriter, records);
stream.Position = 0;
and then you can use
StreamReader reader = new StreamReader(stream);
Response.Write(reader.ReadToEnd);
instead of Response.Write(csv.ToString()) in my first example above.
Don't forget to flush StreamWriter. See example
public MemoryStream CreateCsvFileAsMemoryStream(List<TestItem> testItems) {
var engine = new FileHelperEngine<TestItemCsvMapping>();
var items = testItems.Select(ti => (TestItemCsvMapping)ti).ToList();
engine.HeaderText = engine.GetFileHeader();
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
engine.WriteStream(sw, items);
sw.Flush();
//var reader = new StreamReader(ms);
//ms.Position = 0;
//Console.Write(reader.ReadToEnd());
ms.Position = 0;
return ms;
}
I am having a problem in my app where it reads a PDF from disk, and then has to write it back to a different location later.
The emitted file is not a valid PDF anymore.
In very simplified form, I have tried reading/writing it using
var bytes = File.ReadAllBytes(#"c:\myfile.pdf");
File.WriteAllBytes(#"c:\output.pdf", bytes);
and
var input = new StreamReader(#"c:\myfile.pdf").ReadToEnd();
File.WriteAllText("c:\output.pdf", input);
... and about 100 permutations of the above with various encodings being specified. None of the output files were valid PDFs.
Can someone please lend a hand? Many thanks!!
In C#/.Net 4.0:
using (var i = new FileStream(#"input.pdf", FileMode.Open, FileAccess.Read))
using (var o = File.Create(#"output.pdf"))
i.CopyTo(o);
If you insist on having the byte[] first:
using (var i = new FileStream(#"input.pdf", FileMode.Open, FileAccess.Read))
using (var ms = new MemoryStream())
{
i.CopyTo(ms);
byte[] rawdata = ms.GetBuffer();
using (var o = File.Create(#"output.pdf"))
ms.CopyTo(o);
}
The memory stream may need to be ms.Seek(0, SeekOrigin.Origin) or something like that before the second CopyTo. look it up, or try it out
You're using File.WriteAllText to write your file out.
Try File.WriteAllBytes.