locked
How to Read and then Write to a file.

    Question

  • Hi

    I am trying to read and write tags to a file. Reading tags  no problem,, but when I try to write,, 

    A simple test case

    var file = await KnownFolders.MusicLibrary.GetFileAsync("sampleUnderTest.wav");
    var  content = await ReadFileAsynch(file);
    
    content.Add("newTag","newValue")
    await SubmittFileAsynch(file, content)
    var newContent = await ReadFileAsynch(file);
    
    Assert.NotEqual(content,newContent)

    The Assert throws a Exception because content and newContent are identical.

    This is my SubmittFileAsynch

    public async Task SubmittFileAsynch(StorageFile file, Content content) { var accessStream = await file.OpenAsync(FileAccessMode.ReadWrite); using (accessStream) await CommitAsynch(accessStream, content); } internal async Task CommitAsynch(IRandomAccessStream accessStream, Content content) { List<byte[]> tbw = new List<byte[]>(); using (var InStream = accessStream.AsStreamForRead()) { using (var br = new BinaryReader(InStream)) {

    //Reads file until it reaches the part of the
    //that are going to be modified by content.
    //All data stored in tbw.

    await BuildAsync(br, content, tbw);

    using (var outstream = (accessStream.GetOutputStreamAt(0))) using (var bw = new DataWriter(outstream)) { await CommitAsync(tbw, bw); await bw.FlushAsync(); } } } } private async Task CommitAsync(List<byte[]> tbw, DataWriter bw) { await Task.Run(() => { foreach (byte[] buf in tbw) bw.WriteBytes(buf); }); }

    I can't see what I am doing wrong here,, and are hoping for some help.

    //regards

    //lg


    /regards /lg


    Tuesday, April 22, 2014 3:35 PM

Answers

  • Hi again,,, I am back *smile*

    Finally I solved my problem. There where some threading issues in my code. I changed the write part to:

    using (var bw = new DataWriter(outstream))
    {
        //await CommitAsync(tbw, bw);
        foreach (byte[] buf in tbw)
            bw.WriteBytes(buf);
        
        await bw.StoreAsync();
        bw.DetachStream();
    }
    await outstream.FlushAsync();

    Now it works nicely. I am not sure if there are som part of the code that are redundant,, with respect to the "using" clause.

    If anyone can tip me about some good reading regarding fileIO/ streams etc,,, I would be greatful. All that I found on internet,, was very basic,, 

    Hope this will help someone else.


    /regards /lg

    Tuesday, April 29, 2014 3:34 PM

All replies

  • If you examine the file on disk does it look right? Is there a reason not to use StorageFile's property system?Can you share on your OneDrive a minimal project that reproduces the problem?
    Wednesday, April 23, 2014 2:20 PM
    Owner
  • The file on the disk,,, is the "old" one. It seems like data from tbw never get saved on the disk. Old data are still there when I read the file with other tools. Using the debugger I can tell that tbw contains the information I would like to save to disk.

    I was not aware of the property system,, I will do some reading. 

    It is not a easy thing to reproduce the problem,, but I could share the complete project with you if you cant see anything obvious that is wrong with the code.


    /regards /lg

    Wednesday, April 23, 2014 2:46 PM
  • I wrote this months ago, then never used it, so take it with a big grain.... I realize this is a button event handler, but it might be helpful in debugging.

    private async void SaveFile_Click(object sender, RoutedEventArgs e)
    {
        string message = string.Empty;
    
        FileSavePicker savePicker = new FileSavePicker();
        savePicker.FileTypeChoices.Add("My App", new List<string>() { ".map" });
    
        _storageFile = await savePicker.PickSaveFileAsync();
        if (_storageFile != null)
        {
            // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
            CachedFileManager.DeferUpdates(_storageFile);
    
            // write to file
            await FileIO.WriteTextAsync(_storageFile, _storageFile.Name);
    
            // Let Windows know that we're finished changing the file so the other 
            // app can update the remote version of the file.
            // Completing updates may require Windows to ask for user input.
    
            FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(_storageFile);
            if (status == FileUpdateStatus.Complete)
            {
                message = "File " + _storageFile.Name + " was saved.";
            }
            else
            {
                message = "File " + _storageFile.Name + " couldn't be saved.";
            }
        }
    
        // Only show toast if we have something to show.
        if (!String.IsNullOrEmpty(message))
        {
            ShowToast(message);
        }
    }


    Randy

    Wednesday, April 23, 2014 6:47 PM
  • Could I have your mail address so I can share the project with you,, or are there some other way to share the project?

    /regards /lg


    Thursday, April 24, 2014 6:12 AM
  • I think Rob's suggestion is the best: Post of a minimum version of the problem to OneDrive, then post here where that is and how to download. You'll probably have to dig through the docs to see how to do all this. If it's not clear, maybe Rob could post links. That way, anyone from here can answer. Hopefully, you'll remove the bin directory to remove your executables and make the downloading faster.

    Hope that helps!


    Randy

    Thursday, April 24, 2014 1:04 PM
  • Hi again,,, I am back *smile*

    Finally I solved my problem. There where some threading issues in my code. I changed the write part to:

    using (var bw = new DataWriter(outstream))
    {
        //await CommitAsync(tbw, bw);
        foreach (byte[] buf in tbw)
            bw.WriteBytes(buf);
        
        await bw.StoreAsync();
        bw.DetachStream();
    }
    await outstream.FlushAsync();

    Now it works nicely. I am not sure if there are som part of the code that are redundant,, with respect to the "using" clause.

    If anyone can tip me about some good reading regarding fileIO/ streams etc,,, I would be greatful. All that I found on internet,, was very basic,, 

    Hope this will help someone else.


    /regards /lg

    Tuesday, April 29, 2014 3:34 PM