/// <summary> /// Creates an empty file at a given path. /// </summary> public static async Task CreateEmptyFileAsync(this IAbsFileSystem fileSystem, AbsolutePath path) { fileSystem.CreateDirectory(path.Parent); using (await fileSystem.OpenAsync(path, FileAccess.Write, FileMode.Create, FileShare.None, FileOptions.None, bufferSize: 1).ConfigureAwait(false)) { } }
/// <summary> /// Open the named file asynchronously for reading. /// </summary> /// <exception cref="FileNotFoundException">Throws if the file is not found.</exception> /// <remarks> /// Unlike <see cref="IAbsFileSystem.OpenAsync(AbsolutePath, FileAccess, FileMode, FileShare, FileOptions, int)"/> this function throws an exception if the file is missing. /// </remarks> public static async Task <StreamWithLength> OpenSafeAsync(this IAbsFileSystem fileSystem, AbsolutePath path, FileAccess fileAccess, FileMode fileMode, FileShare share, FileOptions options = FileOptions.None, int bufferSize = FileSystemDefaults.DefaultFileStreamBufferSize) { var stream = await fileSystem.OpenAsync(path, fileAccess, fileMode, share, options, bufferSize); if (stream == null) { throw new FileNotFoundException($"The file '{path}' does not exist."); } return(stream.Value); }
private async Task <PutResult> PutStreamInternalAsync(Context context, Stream stream, ContentHash contentHash, Func <int, AbsolutePath, Task <PutResult> > putFileFunc) { ObjectResult <SessionData> result = await _sessionState.GetDataAsync(); if (!result.Succeeded) { return(new PutResult(result, contentHash)); } int sessionId = result.Data.SessionId; var tempFile = result.Data.TemporaryDirectory.CreateRandomFileName(); try { if (stream.CanSeek) { stream.Position = 0; } using (var fileStream = await _fileSystem.OpenAsync(tempFile, FileAccess.Write, FileMode.Create, FileShare.Delete)) { if (fileStream == null) { throw new ClientCanRetryException(context, $"Could not create temp file {tempFile}. The service may have restarted."); } await stream.CopyToAsync(fileStream); } PutResult putResult = await putFileFunc(sessionId, tempFile); if (putResult.Succeeded) { return(new PutResult(putResult.ContentHash, putResult.ContentSize)); } else if (!_fileSystem.FileExists(tempFile)) { throw new ClientCanRetryException(context, $"Temp file {tempFile} not found. The service may have restarted."); } else { return(new PutResult(putResult, putResult.ContentHash)); } } catch (Exception ex) when(ex is DirectoryNotFoundException || ex is UnauthorizedAccessException) { throw new ClientCanRetryException(context, "Exception thrown during PutStreamInternal. The service may have shut down", ex); } catch (Exception ex) when(!(ex is ClientCanRetryException)) { // The caller's retry policy needs to see ClientCanRetryExceptions in order to properly retry return(new PutResult(ex, contentHash)); } }
/// <summary> /// Tries to read the content from a file <paramref name="absolutePath"/>. /// </summary> /// <returns>Returns <code>null</code> if file does not exist, or content of the file otherwise.</returns> /// <exception cref="Exception">Throws if the IO operation fails.</exception> public static async Task <string?> TryReadFileAsync(this IAbsFileSystem fileSystem, AbsolutePath absolutePath, FileShare fileShare = FileShare.ReadWrite) { using Stream? readLockFile = await fileSystem.OpenAsync(absolutePath, FileAccess.Read, FileMode.Open, fileShare).ConfigureAwait(false); if (readLockFile != null) { using var reader = new StreamReader(readLockFile); return(await reader.ReadToEndAsync().ConfigureAwait(false)); } return(null); }
static async Task openAndClose(IAbsFileSystem fileSystem, AbsolutePath path) { await Task.Yield(); try { // This operation may fail with UnauthorizedAccessException because // the test tries to delete the file in the process. using var f = await fileSystem.OpenAsync(path, FileAccess.Read, FileMode.Open, FileShare.Read | FileShare.Delete); } catch (UnauthorizedAccessException) { } }
/// <inheritdoc /> public async Task <Possible <string, Failure> > ShutdownAsync() { Contract.Requires(!IsShutdown); m_isShutdown = true; try { try { GetStatsResult stats = await m_cache.GetStatsAsync(new Context(m_logger)); if (stats.Succeeded) { using (Stream fileStream = await m_fileSystem.OpenAsync(m_statsFile, FileAccess.ReadWrite, FileMode.CreateNew, FileShare.None)) { using (StreamWriter sw = new StreamWriter(fileStream)) { foreach (KeyValuePair <string, long> stat in stats.CounterSet.ToDictionaryIntegral()) { await sw.WriteLineAsync($"{stat.Key}={stat.Value}"); } } } } else { m_logger.Debug($"Stats call failed {stats.ErrorMessage}"); } } #pragma warning disable ERP022 // Unobserved exception in generic exception handler catch { } #pragma warning restore ERP022 // Unobserved exception in generic exception handler BoolResult shutdownResult = await m_cache.ShutdownAsync(new Context(m_logger)); if (shutdownResult.Succeeded) { return(CacheId); } return(new CacheFailure(shutdownResult.ErrorMessage)); } finally { Dispose(); } }
/// <summary> /// Calls <see cref="IAbsFileSystem.OpenAsync(AbsolutePath, FileAccess, FileMode, FileShare, FileOptions, int)" /> with the default buffer stream size. /// </summary> public static Task <StreamWithLength?> OpenAsync(this IAbsFileSystem fileSystem, AbsolutePath path, FileAccess fileAccess, FileMode fileMode, FileShare share) { return(fileSystem.OpenAsync(path, fileAccess, fileMode, share, FileOptions.None, DefaultFileStreamBufferSize)); }