/******************************************************************************* * Copyright by the contributors to the Dafny Project * SPDX-License-Identifier: MIT *******************************************************************************/ namespace DafnyLibraries { using System; using System.IO; using Dafny; public class FileIO { /// /// Attempts to read all bytes from the file at the given path, and outputs the following values: /// /// /// isError /// /// true iff an exception was thrown during path string conversion or when reading the file /// /// /// /// bytesRead /// /// the sequence of bytes read from the file, or an empty sequence if isError is true /// /// /// /// errorMsg /// /// the error message of the thrown exception if isError is true, or an empty sequence otherwise /// /// /// /// /// We output these values individually because Result is not defined in the runtime but instead in library code. /// It is the responsibility of library code to construct an equivalent Result value. /// public static void INTERNAL_ReadBytesFromFile(ISequence path, out bool isError, out ISequence bytesRead, out ISequence errorMsg) { isError = true; bytesRead = Sequence.Empty; errorMsg = Sequence.Empty; try { bytesRead = Helpers.SeqFromArray(File.ReadAllBytes(path?.ToString())); isError = false; } catch (Exception e) { errorMsg = Helpers.SeqFromArray(e.ToString().ToCharArray()); } } /// /// Attempts to write all given bytes to the file at the given path, creating nonexistent parent directories as necessary, /// and outputs the following values: /// /// /// isError /// /// true iff an exception was thrown during path string conversion or when writing to the file /// /// /// /// errorMsg /// /// the error message of the thrown exception if isError is true, or an empty sequence otherwise /// /// /// /// /// We output these values individually because Result is not defined in the runtime but instead in library code. /// It is the responsibility of library code to construct an equivalent Result value. /// public static void INTERNAL_WriteBytesToFile(ISequence path, ISequence bytes, out bool isError, out ISequence errorMsg) { isError = true; errorMsg = Sequence.Empty; try { string pathStr = path?.ToString(); CreateParentDirs(pathStr); File.WriteAllBytes(pathStr, bytes.CloneAsArray()); isError = false; } catch (Exception e) { errorMsg = Helpers.SeqFromArray(e.ToString().ToCharArray()); } } /// /// Creates the nonexistent parent directory(-ies) of the given path. /// private static void CreateParentDirs(string path) { string parentDir = Path.GetDirectoryName(Path.GetFullPath(path)); Directory.CreateDirectory(parentDir); } } }