I have a Problem using the FileSavePicker.
I always thought, the FileSavePicker would replace the file, when you Chose the Name of an existing file. It even asks "theres already some file with that Name, do you want to replace it?" when you click on save.
In the next steps of my program, I open the StorageFile and write a stream to it. My program works just fine, when the new stream is LONGER than the CURRENT stream, but will create corrupt files, when it is shorter (well of course leaving some Bytes at the end of the file that will not get overwritten or deleted).
So my question is: How do I enforce that replace mechanism of the FileSavePicker?
FileSavePicker filePicker = new FileSavePicker();
filePicker.SuggestedFileName = "Some File Name";
filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
filePicker.FileTypeChoices.Add("Pdf File", new List<string>(){ ".pdf" });
StorageFile saveFile = await filePicker.PickSaveFileAsync();
I will then give the SaveFile as a Parameter to a new class. That creates a pdf document using iTextSharp.
var stream = await saveFile.OpenAsync(FileAccessMode.ReadWrite);
doc = new Document();
writer = new PdfCopy(doc, stream.AsStream());
So yeah. It works fine when the new file is bigger than the previous. When you get to the file save picker, pick a file and click on "Save" it even asks you, if you want to replace the file, so I thought, it would actually replace the file... :/
Thanks for your help!
You open it for ReadWrite
which preserves the previous contents. In order to truncate you need to cast to a FileRandomAccessStream
and then set the Size
to zero:
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add(".txt");
var file = await picker.PickSingleFileAsync();
var stream = (await file.OpenAsync(FileAccessMode.ReadWrite)) as FileRandomAccessStream;
stream.Size = 0;
var writer = new DataWriter(stream.GetOutputStreamAt(0));
writer.WriteString("Hello\r\n");
await writer.StoreAsync();