Esempio n. 1
0
        public static void Serializer(Object obj, Java.IO.File file)
        {
            Task.Run(async() =>
            {
                // Wait for file to be free
                while (FileUtils.IsFileLocked(file))
                {
                    await Task.Delay(100).ConfigureAwait(false);
                }

                var mFile             = new AtomicFile(file);
                Stream fStream        = null;
                JsonTextWriter writer = null;

                try
                {
                    fStream = mFile.StartWrite();

                    writer = new JsonTextWriter(new StreamWriter(fStream))
                    {
                        CloseOutput = false,
                    };

                    var serializer = JsonSerializer.Create(DefaultSettings);
                    serializer.Serialize(writer, obj);
                    await writer.FlushAsync().ConfigureAwait(false);
                    mFile.FinishWrite(fStream);
                }
                catch (Exception ex)
                {
                    Logger.WriteLine(LoggerLevel.Error, ex, "SimpleWeather: JSONParser: error serializing or with file");

                    if (mFile != null && fStream != null)
                    {
                        mFile.FailWrite(fStream);
                    }
                }
                finally
                {
                    mFile?.Dispose();
                    writer?.Close();
                }
            }).ConfigureAwait(false);
        }
Esempio n. 2
0
        public static async Task WriteFile(String data, File file)
        {
            using (AtomicFile mFile = new AtomicFile(file))
            {
                // Wait for file to be free
                while (IsFileLocked(file))
                {
                    await Task.Delay(100);
                }

                using (System.IO.Stream outputStream = mFile.StartWrite())
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(outputStream))
                    {
                        // Clear file before writing
                        outputStream.SetLength(0);

                        await writer.WriteAsync(data);

                        await writer.FlushAsync();

                        mFile.FinishWrite(outputStream);
                    }
            }
        }