简体   繁体   English

如何覆盖UWP中的文件?

[英]How can I overwrite a file in UWP?

I tried to overwrite a current file in UWP using FileSavePicker. 我试图使用FileSavePicker覆盖UWP中的当前文件。 I refered to this: https://msdn.microsoft.com/zh-cn/windows/uwp/files/quickstart-reading-and-writing-files But when I use a shorter file to overwrite a longer file, there comes a problem: the extra part of the old file(longer) isn't deleted, like this: 我指的是: https : //msdn.microsoft.com/zh-cn/windows/uwp/files/quickstart-reading-and-writing-files但是当我使用较短的文件来覆盖较长的文件时,会出现问题:旧文件的多余部分(较长)没有被删除,像这样:

The old file: 旧文件:

abcdefg

And the file I want to save: 和我要保存的文件:

hij

But after saving operations, I get this: 但是保存操作后,我得到了:

hijdefg

My code is here: 我的代码在这里:

        private async void Save_Click(object sender, RoutedEventArgs e)
    {
        XmlDocument Line = SaveToXml();

        //Save it
        FileSavePicker fileSaving = new FileSavePicker();
        fileSaving.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
        fileSaving.SuggestedFileName = "NewLine";
        fileSaving.FileTypeChoices.Add("Simple Line Files", new List<string>() { ".Line" });
        StorageFile file = await fileSaving.PickSaveFileAsync();

        if (file != null)
        {
            CachedFileManager.DeferUpdates(file);
            var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
            //var stream = await file.OpenStreamForWriteAsync();
            using (var outputStream = stream.GetOutputStreamAt(0))
            {
                using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))
                {
                    string xmlDoc = Line.OuterXml;
                    Debug.WriteLine(Line.OuterXml);
                    dataWriter.WriteString(xmlDoc);
                    await dataWriter.StoreAsync();
                    await outputStream.FlushAsync();
                }
            }
            stream.Dispose();
        }
    }

Thanks for helping me! 感谢您的帮助!

Your code var outputStream = stream.GetOutputStreamAt(0) returns an output stream at the begin location in your file stream. 您的代码var outputStream = stream.GetOutputStreamAt(0)返回文件流中开始位置的输出流。 Now when you write to the file, it will replace the file from the location you set. 现在,当您写入文件时,它将从您设置的位置替换文件。 When the new string you want to write is less than the old string in the file, it can not replace all the old string. 当您要写入的新字符串小于文件中的旧字符串时,它不能替换所有旧字符串。 So using this method, you can't ensure that every letters can be replaced in the old file. 因此,使用这种方法,您不能确保可以在旧文件中替换所有字母。

You can use FileIO.WriteTextAsync(IStorageFile, String) method to write text to the specified file. 您可以使用FileIO.WriteTextAsync(IStorageFile, String)方法将文本写入指定的文件。 It can overwrite the old file. 它可以覆盖旧文件。

For example: 例如:

private async void Save_Click(object sender, RoutedEventArgs e)
{
    FileSavePicker savePicker = new FileSavePicker();
    savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    savePicker.FileTypeChoices.Add("Simple Line Files", new List<string>() { ".line" });
    savePicker.SuggestedFileName = "NewLine";
    StorageFile file = await savePicker.PickSaveFileAsync();
    if (file != null)
    {
        CachedFileManager.DeferUpdates(file);
        await FileIO.WriteTextAsync(file, "hello");
        FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
    }
}

You can also call Stream.SetLength(0) immediately after opening the stream to clear it before you start writing. 您也可以在打开流后立即调用Stream.SetLength(0)清除流,然后再开始写入。

var streamToWrite = await file.OpenStreamForWriteAsync().ConfigureAwait(false);
streamToWrite.SetLength(0);
using (var streamWriter = new StreamWriter(streamToWrite))
{
    streamWriter.Write(data);
    streamWriter.Flush();                        
}

Before calling OpenStreamForWriteAsync() use FileIO.WriteBytesAsync and write a zero byte array. 在调用OpenStreamForWriteAsync()之前,请使用FileIO.WriteBytesAsync并写入一个零字节数组。 This will clear the file. 这将清除文件。

public async Task<Stream> ClearAndGetStream(StorageFile storageFile)
{
    await FileIO.WriteBytesAsync(storageFile, new byte[0]);
    return await storageFile.OpenStreamForWriteAsync();
}

While still using DataWriter, there is a solution. 仍在使用DataWriter时,有一个解决方案。 I had the same exact problem as you and solved it by doing this. 我遇到了与您完全相同的问题,并通过执行此操作解决了问题。

Replace: 更换:

await dataWriter.StoreAsync();

With: 附:

stream.size = await dataWriter.StoreAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM