Thursday, September 13, 2018

Make an artificially fat flat file in C# for your own testing from a slimmer file.

using System;
using System.IO;
using System.Threading.Tasks;
using MyOwnStuff.Core.Interfaces;
using MyOwnStuff.Core.Objects;
namespace MyOwnStuff.Infrastructure.ExternalDependencies
{
   public class FileWriting : IFileWriting
   {
      public async void FattenFile(byte[] bytes, string fileName, InitialDetails initialDetails,
            Action<Alert> alertAction)
      {
         int counter = 0;
         string filePath = String.Format("{0}\\{1}", initialDetails.ToPath, fileName);
         while (counter < initialDetails.TimesToDuplicateInFattening)
         {
            if (counter == 0)
            {
               await Task.Run(() => { FlattenFile(bytes, filePath, initialDetails,
                     FileMode.Create); });
            }
            else
            {
               await Task.Run(() => { FlattenFile(bytes, filePath, initialDetails,
                     FileMode.Append); });
            }
            counter++;
            if (counter == initialDetails.TimesToDuplicateInFattening)
            {
               alertAction(new Alert(String.Format("The file has been successfully written to:
                     {0}\\{1}", initialDetails.ToPath, fileName), false));
            }
            else
            {
               alertAction(new Alert(String.Format("Writing pass {0} of {1} to {2}\\{3}.", counter,
                     initialDetails.TimesToDuplicateInFattening, initialDetails.ToPath, fileName),
                     false));
            }
         }
      }
      
      private void FlattenFile(byte[] bytes, string filePath, InitialDetails initialDetails,
            FileMode fileMode)
      {
         using (Stream stream = new FileStream(filePath, fileMode))
         {
            stream.Write(bytes, 0, bytes.Length);
         }
      }
   }

}

 
 

Awesome! Things to note include that the public method signature may be async but the matching method in the interface will not use the async keyword, the last of the actions called seems to clobber the message I just get back from the method calling the public method above wherein both messages get put to a label in a WinFroms app, and that, finally, I read online that you have to asynchronously make labels in a WinForms app listen like so, but this is really no longer the case with async/await:

this.foo.BeginInvoke(new Action(() => { this.foo.Text = "bar"; }));

No comments:

Post a Comment