public void TestParallelFor(FileAccessMode mode) { var count = 0; var ipsAndResults = new Dictionary<IPAddress, string>(); var rand = new Random(); using (var reader = new Reader(Path.Combine("..", "..", "TestData", "GeoLite2-City.mmdb"), mode)) { while (count < 10000) { var ip = new IPAddress(rand.Next(int.MaxValue)); var resp = reader.Find(ip); if (resp != null) { ipsAndResults.Add(ip, resp.ToString()); count++; } } var ips = ipsAndResults.Keys.ToArray(); var start = DateTime.Now; Parallel.For(0, ips.Length, i => { var ipAddress = ips[i]; var result = reader.Find(ipAddress); var resultString = result.ToString(); var expectedString = ipsAndResults[ipAddress]; if (resultString != expectedString) throw new Exception(string.Format("Non-matching result. Expected {0}, found {1}", expectedString, resultString)); }); var stop = DateTime.Now; Console.WriteLine("Requests per second: " + count / (stop - start).TotalSeconds); } }
public void TestManyOpens(FileAccessMode mode) { Parallel.For(0, 1000, i => { var reader = new Reader(Path.Combine("..", "..", "TestData", "GeoLite2-City.mmdb"), mode); }); }
public void TestParallelFor(FileAccessMode mode) { var count = 0; var ipsAndResults = new Dictionary<IPAddress, string>(); var rand = new Random(); using (var reader = new Reader(Path.Combine("..", "..", "TestData", "GeoLite2-City.mmdb"), mode)) { while (count < 10000) { var ip = new IPAddress(rand.Next(int.MaxValue)); var resp = reader.Find(ip); if (resp != null && !ipsAndResults.ContainsKey(ip)) { ipsAndResults.Add(ip, resp.ToString()); count++; } } var ips = ipsAndResults.Keys.ToArray(); Parallel.For(0, ips.Length, i => { var ipAddress = ips[i]; var result = reader.Find(ipAddress); var resultString = result.ToString(); var expectedString = ipsAndResults[ipAddress]; if (resultString != expectedString) throw new Exception($"Non-matching result. Expected {expectedString}, found {resultString}"); }); } }
public async Task<Stream> CreateStreamAsync(FileAccessMode accesMode) { Uri uri = new Uri(urlString, UriKind.Absolute); var file = await StorageFile.GetFileFromApplicationUriAsync(uri); var stream = await file.OpenAsync(accesMode); return stream.AsStream(); }
internal TorrentFileStream GetStream(TorrentFile file, FileAccessMode access) { var fullPath = file.FullPath; var asyncTokens = GetAsyncTokens(fullPath); try { asyncTokens.CancellationTokenSource.Token.ThrowIfCancellationRequested(); var s = FindStream(fullPath); if (s != null) { // If we are requesting write access and the current stream does not have it if (access == FileAccessMode.ReadWrite && !s.CanWrite) { Debug.WriteLine("Didn't have write permission - reopening"); CloseAndRemove(s); } else { lock (_locker) { // Place the filestream at the end so we know it's been recently used _streams.Remove(s); _streams.Add(s); } return s; } } try { var result = OpenStreamAsync(file, access, asyncTokens).Result; file.Exists = true; s = new TorrentFileStream(file, result) { Size = (ulong) file.Length }; Add(s); } catch (AggregateException ex) { if (ex.InnerException is OperationCanceledException || ex.InnerException is UnauthorizedAccessException) throw ex.InnerException; throw; } return s; } finally { if (asyncTokens != null) { asyncTokens.SemaphoreSlim.Release(); if (asyncTokens.CancellationTokenSource.IsCancellationRequested) Clear(fullPath); } } }
public void TestManyOpens(FileAccessMode mode) { Parallel.For(0, 50, i => { using (var reader = new Reader(Path.Combine("..", "..", "TestData", "GeoLite2-City.mmdb"), mode)) { reader.Find("1.1.1.1"); } }); }
public static bool IsTransitionState(FileAccessMode mode) { switch(mode) { case FileAccessMode.SwitchingToDisabled: case FileAccessMode.SwitchingToReadOnly: case FileAccessMode.SwitchingToReadWrite: return true; default: return false; } }
public static bool TransitionsToState(FileAccessMode targetState, FileAccessMode currentState) { switch(targetState) { case FileAccessMode.ReadOnly: return currentState == FileAccessMode.SwitchingToReadOnly; case FileAccessMode.ReadWrite: return currentState == FileAccessMode.SwitchingToReadWrite; case FileAccessMode.Disabled: return currentState == FileAccessMode.SwitchingToDisabled; default: return false; } }
internal TorrentFileStream GetStream(TorrentFile file, FileAccessMode access) { TorrentFileStream s = FindStream(file.FullPath); if (s != null) { // If we are requesting write access and the current stream does not have it if (((access & FileAccessMode.ReadWrite) == FileAccessMode.ReadWrite) && !s.CanWrite) { Logger.Log (null, "Didn't have write permission - reopening"); CloseAndRemove(s); s = null; } else { // Place the filestream at the end so we know it's been recently used list.Remove(s); list.Add(s); } } if (s == null) { if (!File.Exists(file.FullPath)) { Directory.CreateDirectory (Path.GetDirectoryName(file.FullPath)); SparseFile.CreateSparse (file.FullPath, file.Length); } s = new TorrentFileStream (file, access); // Ensure that we truncate existing files which are too large if (s.Length > file.Length) { if (!s.CanWrite) { s.Dispose(); s = new TorrentFileStream(file, FileAccessMode.ReadWrite); } s.SetLength(file.Length); } Add(s); } return s; }
/// <summary> /// Create (or open) a new file in the folder. /// </summary> /// <param name="name"> /// The name of the file to open or create. The file name must not contain path /// separators. /// </param> /// <param name="access"> /// The access mode to open the file with. /// </param> /// <param name="options"> /// Creation options. /// </param> /// <returns>A Stream instance to read or write to the file.</returns> public Stream CreateFile(string name, FileAccessMode access, CreationOptions options) { bool exists = FileExists(name); string target = Path.Combine(m_path, name); switch (options) { case CreationOptions.FailIfExists: if (exists) throw new InvalidOperationException(String.Format("File '{0}' exists and {1} was specified.", target, options)); break; case CreationOptions.OpenIfExists: break; case CreationOptions.ReplaceExisting: if (exists) File.Delete(target); break; } // Now open the stream return File.Open(target, FileMode.OpenOrCreate, (access == FileAccessMode.Read) ? FileAccess.Read : FileAccess.ReadWrite, FileShare.None); }
Stream IFileSystem.OpenFile(string path, FileAccessMode mode) { if (mode == FileAccessMode.None) throw new ArgumentException("Can't open a file stream without any access capabilities."); FileAccess access; switch (mode) { default: case FileAccessMode.Read: access = FileAccess.Read; break; case FileAccessMode.Write: access = FileAccess.Write; break; case FileAccessMode.ReadWrite: access = FileAccess.ReadWrite; break; } return File.Open(path, FileMode.Open, access, FileShare.ReadWrite); }
public override void PlaceFileStop(Context context, ContentHash contentHash, PlaceFileResult result, AbsolutePath path, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, Severity successSeverity) { if (_eventSource.IsEnabled()) { _eventSource.PlaceFileStop(context.Id.ToString(), (int)result.Code, result.ErrorMessage); } base.PlaceFileStop(context, contentHash, result, path, accessMode, replacementMode, realizationMode, successSeverity: DiagnosticLevelSeverity); }
internal static async Task <FileRandomAccessStream> CreateFromSafUriAsync(Android.Net.Uri fileUri, FileAccessMode access) => new FileRandomAccessStream(await SafStream.CreateAsync(fileUri, access));
public Task <IEnumerable <Task <Indexed <PlaceFileResult> > > > PlaceFileAsync(Context context, IReadOnlyList <ContentHashWithPath> hashesWithPaths, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal) { throw new NotImplementedException(); }
public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions) => new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 4096, GetFileOptions(fileOpenOptions));
/// <inheritdoc /> protected override Task <PlaceFileResult> PlaceFileCoreAsync(OperationContext operationContext, ContentHash contentHash, AbsolutePath path, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter) { return(InnerSession.PlaceFileAsync(operationContext, contentHash, path, accessMode, replacementMode, realizationMode, operationContext.Token, urgencyHint)); }
private static int uv_fs_open(Loop loop, IntPtr req, string path, FileAccessMode rw, FileOpenMode open, FilePermissions permissions, uv_fs_cb cb) { return Uvi.uv_fs_open(loop.Handle, req, path, (int)rw | (int)open, (int)permissions, cb); }
public IAsyncOperation<IRandomAccessStream> OpenAsync(FileAccessMode accessMode) { return null; }
unsafe byte open_directory(int channel, byte *filename) { using (BytePtr buf = new BytePtr(Encoding.ASCII.GetBytes("\u0001\u0004\u0001\u0001\u0000\u0000\u0012\u0022 \u0022 00 2A\0")), pattern = new BytePtr(IEC.NAMEBUF_LENGTH)) { //char str[NAMEBUF_LENGTH]; byte * p, q; int i; FileAccessMode filemode = FileAccessMode.FMODE_READ; FileType filetype = FileType.FTYPE_PRG; bool wildflag = false; string str; // Special treatment for "$0" if (filename[0] == '0' && filename[1] == 0) { filename += 1; } // Convert filename ('$' already stripped), filemode/type are ignored convert_filename(filename, pattern, ref filemode, ref filetype, ref wildflag); DirectoryInfo dir = new DirectoryInfo(dir_path); if (!dir.Exists) { set_error(ErrorCode1541.ERR_NOTREADY); return((byte)C64StatusCode.ST_OK); } FileSystemInfo[] files = dir.GetFileSystemInfos(); file[channel] = new FileStream(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite); p = (byte *)buf.Pointer + 8; for (i = 0; i < 16 & i < dir_title.Length; i++) { *p++ = conv_to_64((byte)dir_title[i], false); } file[channel].Write(buf, 0, 32); IEnumerator fenum = files.GetEnumerator(); while (fenum.MoveNext() && (((FileSystemInfo)fenum.Current).Name == "." || ((FileSystemInfo)fenum.Current).Name == "..")) { ; } do { FileSystemInfo fsi = (FileSystemInfo)fenum.Current; if (match(pattern.ToString(), fsi.Name)) { // Clear line with spaces and terminate with null byte for (i = 0; i < buf.Length; i++) { buf[i] = (byte)' '; } buf[31] = 0; p = buf; *p++ = 0x01; // Dummy line link *p++ = 0x01; if (fsi is FileInfo) { FileInfo fi = (FileInfo)fsi; // Calculate size in blocks (254 bytes each) i = (int)((fi.Length + 254) / 254); *p++ = (byte)(i & 0xff); *p++ = (byte)((i >> 8) & 0xff); p++; if (i < 10) { p++; // Less than 10: add one space } if (i < 100) { p++; // Less than 100: add another space } str = fi.Name; // Convert and insert file name *p++ = (byte)'\"'; q = p; for (i = 0; i < 16 && i < str.Length; i++) { *q++ = conv_to_64((byte)str[i], true); } *q++ = (byte)'\"'; p += 18; } // File type if (fsi is DirectoryInfo) { *p++ = (byte)'D'; *p++ = (byte)'I'; *p++ = (byte)'R'; } else { *p++ = (byte)'P'; *p++ = (byte)'R'; *p++ = (byte)'G'; } // Write line file[channel].Write(buf, 0, 32); } } while (fenum.MoveNext()); } // Final line file[channel].Write(Encoding.ASCII.GetBytes("\u0001\u0001\0\0BLOCKS FREE. \0\0\0"), 0, 32); file[channel].Position = 0; read_char[channel] = (byte)file[channel].ReadByte(); return((byte)C64StatusCode.ST_OK); }
byte open_file(int channel, BytePtr filename) { using (BytePtr plainname = new BytePtr(256)) { FileAccessMode filemode = FileAccessMode.FMODE_READ; FileType filetype = FileType.FTYPE_PRG; bool wildflag = false; FileMode fmode = FileMode.Open; FileAccess faccess = FileAccess.Read; unsafe { convert_filename(filename, plainname, ref filemode, ref filetype, ref wildflag); } // Channel 0 is READ PRG, channel 1 is WRITE PRG if (channel == 0) { filemode = FileAccessMode.FMODE_READ; filetype = FileType.FTYPE_PRG; } else if (channel == 1) { filemode = FileAccessMode.FMODE_WRITE; filetype = FileType.FTYPE_PRG; } // Wildcards are only allowed on reading if (wildflag) { if (filemode != FileAccessMode.FMODE_READ) { set_error(ErrorCode1541.ERR_SYNTAX33); return((byte)C64StatusCode.ST_OK); } find_first_file(plainname); } // Select fopen() mode according to file mode switch (filemode) { case FileAccessMode.FMODE_READ: fmode = FileMode.Open; faccess = FileAccess.Read; break; case FileAccessMode.FMODE_WRITE: fmode = FileMode.OpenOrCreate; faccess = FileAccess.ReadWrite; break; case FileAccessMode.FMODE_APPEND: fmode = FileMode.Append; faccess = FileAccess.ReadWrite; break; } try { string fullpath = Path.Combine(dir_path, plainname.ToString()); file[channel] = new FileStream(fullpath, fmode, faccess); if (filemode == FileAccessMode.FMODE_READ) // Read and buffer first byte { read_char[channel] = (byte)file[channel].ReadByte(); } else { Environment.CurrentDirectory = Assembly.GetExecutingAssembly().Location; } } catch (DirectoryNotFoundException) { set_error(ErrorCode1541.ERR_NOTREADY); } catch (FileNotFoundException) { set_error(ErrorCode1541.ERR_FILENOTFOUND); } } return((byte)C64StatusCode.ST_OK); }
/// <inheritdoc /> protected override Task <IEnumerable <Task <Indexed <PlaceFileResult> > > > PlaceFileCoreAsync(OperationContext operationContext, IReadOnlyList <ContentHashWithPath> hashesWithPaths, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter) => Task.FromResult(hashesWithPaths.Select((hash, i) => Task.FromResult(new PlaceFileResult(PlaceFileResult.ResultCode.NotPlacedContentNotFound).WithIndex(i))));
/// <inheritdoc /> protected override Task <PlaceFileResult> PlaceFileCoreAsync(OperationContext operationContext, ContentHash contentHash, AbsolutePath path, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter) => Task.FromResult(new PlaceFileResult(PlaceFileResult.ResultCode.NotPlacedContentNotFound));
protected override Task <IEnumerable <Task <Indexed <PlaceFileResult> > > > PlaceFileCoreAsync(OperationContext context, IReadOnlyList <ContentHashWithPath> hashesWithPaths, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter) => throw new NotImplementedException();
internal void PlaceFile ( [Description("Cache root directory path (using in-process cache)")] string cachePath, [Description("Cache name (using cache service)")] string cacheName, [Required, Description("Content hash value of referenced content to place")] string hash, [Required, Description("Path to destination file")] string path, [Description(HashTypeDescription)] string hashType, [DefaultValue(FileAccessMode.ReadOnly)] FileAccessMode accessMode, [DefaultValue(FileReplacementMode.ReplaceExisting)] FileReplacementMode replacementMode, [DefaultValue(FileRealizationMode.HardLink)] FileRealizationMode realizationMode, [DefaultValue(false), Description("Stream bytes if true")] bool useStream, [Description("File name where the GRPC port can be found when using cache service. 'CASaaS GRPC port' if not specified.")] string grpcPortFileName, [Description("The GRPC port."), DefaultValue(0)] int grpcPort ) { var ht = GetHashTypeByNameOrDefault(hashType); var contentHash = new ContentHash(ht, HexUtilities.HexToBytes(hash)); var filePath = new AbsolutePath(path); ServiceClientRpcConfiguration rpcConfig = null; if (cacheName != null) { if (grpcPort == 0) { grpcPort = Helpers.GetGrpcPortFromFile(_logger, grpcPortFileName); } rpcConfig = new ServiceClientRpcConfiguration(grpcPort); } RunContentStore(cacheName, cachePath, rpcConfig, async(context, session) => { if (useStream) { var r = await session.OpenStreamAsync(context, contentHash, CancellationToken.None).ConfigureAwait(false); if (r.Succeeded) { using (r.Stream) { using (var fileStream = File.OpenWrite(filePath.Path)) { await r.Stream.CopyToAsync(fileStream); _tracer.Always(context, "Success"); } } } else { _tracer.Error(context, r.ToString()); } } else { var r = await session.PlaceFileAsync( context, contentHash, filePath, accessMode, replacementMode, realizationMode, CancellationToken.None).ConfigureAwait(false); if (!r.Succeeded) { _tracer.Error(context, r.ToString()); } else { _tracer.Always(context, "Success"); } } }); }
public FileRandomAccessStream(string path, global::Windows.Storage.FileAccessMode accessMode) { _path = path; _accessMode = accessMode; _source = File.OpenRead(path); }
/// <summary> /// Opens a file according to the FileAccessMode provided and creates /// a stream object for manipulating it. /// </summary> /// <remarks> /// Open() will create a file if it does not exist and the method is /// passed a writable FileAccessMode. If passed FileAccessMode.Read, /// however, a non-existent file will trigger an exception. /// </remarks> /// <param name="file">The file to open as a stream.</param> /// <param name="accessMode"> /// The access mode with which to open this file. /// </param> /// <returns>A stream corresponding to this file.</returns> public abstract Stream Open(FilePath file, FileAccessMode accessMode);
/// <inheritdoc /> public Task <PlaceFileResult> PlaceFileAsync(Context context, ContentHash contentHash, AbsolutePath path, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, CancellationToken cts, UrgencyHint urgencyHint) { return(_innerCacheSession.PlaceFileAsync(context, contentHash, path, accessMode, replacementMode, realizationMode, cts, urgencyHint)); }
public TorrentFileStream(TorrentFile file, FileAccessMode access) { this.file = file; }
public Task <PlaceFileResult> PlaceFileAsync(Context context, ContentHash contentHash, AbsolutePath destinationPath, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, PinRequest?pinRequest = null) { throw new NotImplementedException(); }
public Task <IEnumerable <Task <Indexed <PlaceFileResult> > > > PlaceFileAsync(Context context, IReadOnlyList <ContentHashWithPath> placeFileArgs, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, PinRequest?pinRequest = null) { throw new NotImplementedException(); }
public JarFile(FileAccessMode fileAccessMode, string jarFilePath) : this(fileAccessMode, jarFilePath, 50) { }
public IAsyncOperation <IRandomAccessStream> OpenAsync(FileAccessMode accessMode) => AsyncOperation <IRandomAccessStream> .FromTask(async (ct, _) => await _impl.Open(ct, accessMode, StorageOpenOptions.AllowReadersAndWriters));
/// <inheritdoc /> protected override Task <IEnumerable <Task <Indexed <PlaceFileResult> > > > PlaceFileCoreAsync(OperationContext operationContext, IReadOnlyList <ContentHashWithPath> hashesWithPaths, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, UrgencyHint urgencyHint, Counter retryCounter) { return(InnerSession.PlaceFileAsync(operationContext, hashesWithPaths, accessMode, replacementMode, realizationMode, operationContext.Token, urgencyHint)); }
public async static Task<IRandomAccessStream> GetFileRandomAccessStream(string fileName, FileAccessMode accessMode) { var file = await GetFileAccess(fileName); return await file.OpenAsync(accessMode); }
public Task <PlaceFileResult> PlaceFileAsync(Context context, ContentHash contentHash, AbsolutePath path, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal) { FilePlacedParams.Add(new Tuple <ContentHash, AbsolutePath, FileAccessMode, FileReplacementMode, FileRealizationMode>(contentHash, path, accessMode, replacementMode, realizationMode)); return(Task.FromResult(new PlaceFileResult(PinResult.Success))); }
internal TorrentFileStream GetStream(TorrentFile file, FileAccessMode access) { return streamsBuffer.GetStream(file, access); }
public void Open(string path, FileAccessMode rw, FileOpenMode open, FilePermissions permissions) { if (this.Status != FileHandleStatus.Closed) return; var req = this.CreateRequest(); try { CheckError(Uvi.uv_fs_open(this.Loop.Handle, req, path, rw, open, permissions, this.OnOpen)); this.Status = FileHandleStatus.Opening; } catch (Exception) { this.FreeRequest(req, false); throw; } }
public override Stream Open(FilePath file, FileAccessMode accessMode) { if (file.RawPathSegments.Length < 2) { throw new InvalidOperationException("The root and mount points cannot " + "be opened."); } FilePath sub; FileSystem fs = TransformPathToMountedPath(file, out sub); return fs.Open(sub, accessMode); }
public IAsyncOperation <IRandomAccessStream> OpenAsync(FileAccessMode accessMode, StorageOpenOptions options) => AsyncOperation <IRandomAccessStream> .FromTask(async (ct, _) => await _impl.Open(ct, accessMode, options));
/// <inheritdoc /> public Task <IEnumerable <Task <Indexed <PlaceFileResult> > > > PlaceFileAsync(Context context, IReadOnlyList <ContentHashWithPath> hashesWithPaths, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal) { return(_contentReadOnlySession.PlaceFileAsync(context, hashesWithPaths, accessMode, replacementMode, realizationMode, cts, urgencyHint)); }
public FileStream(string path, FileAccessMode read) { throw new NotImplementedException(); }
public override Stream Open(FilePath file, FileAccessMode accessMode) { if (accessMode == FileAccessMode.Read) { return this.BaseFileSystem.Open(file, accessMode); } throw new UnauthorizedAccessException("Cannot modify files or directories through a ReadOnlyFileSystem."); }
/// <summary> /// Opens an existing file at the specified path and returns a <see cref="System.IO.Stream"/> to it. /// </summary> /// <param name="path"></param> /// <param name="mode"></param> public static Stream Open(string path, FileAccessMode mode) { if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("The specified path is null or whitespace-only."); PathOp.CheckInvalidPathChars(path); return DualityApp.SystemBackend.FileSystem.OpenFile(path, mode); }
public virtual async Task <IRandomAccessStream> GetRandomAccessStreamFromFileAsync(FileAccessMode Mode) { return(await FileRandomAccessStream.OpenAsync(Path, Mode, StorageOpenOptions.AllowReadersAndWriters, FileOpenDisposition.OpenExisting)); }
Stream IFileSystem.OpenFile(string path, FileAccessMode mode) { throw new BackendException(string.Format("Can't open non-existent file '{0}'.", path)); }
internal TorrentFileStream GetStream(TorrentFile file, FileAccessMode access) { if (access == FileAccessMode.Read && !Exists(file)) return null; return _streamsBuffer.GetStream(file, access); }
private static FileAccess ToFileAccess(FileAccessMode accessMode) => accessMode switch {
/// <summary> /// Initializes a new instance of the <see cref="Reader" /> class. /// </summary> /// <param name="file">The MaxMind DB file.</param> /// <param name="mode">The mode by which to access the DB file.</param> public Reader(string file, FileAccessMode mode) : this(BufferForMode(file, mode)) { _fileName = file; }
unsafe void convert_filename(BytePtr srcname, BytePtr destname, ref FileAccessMode filemode, ref FileType filetype) { byte* p; // Search for ':', p points to first character after ':' if ((p = CharFunctions.strchr(srcname, ':')) != null) p++; else p = srcname; // Remaining string -> destname CharFunctions.strncpy(destname, srcname, p); // Look for mode parameters seperated by ',' p = destname; while ((p = CharFunctions.strchr(p, ',')) != null) { // Cut string after the first ',' *p++ = 0; switch ((Char)(*p)) { case 'P': filetype = FileType.FTYPE_PRG; break; case 'S': filetype = FileType.FTYPE_SEQ; break; case 'U': filetype = FileType.FTYPE_USR; break; case 'L': filetype = FileType.FTYPE_REL; break; case 'R': filemode = FileAccessMode.FMODE_READ; break; case 'W': filemode = FileAccessMode.FMODE_WRITE; break; case 'A': filemode = FileAccessMode.FMODE_APPEND; break; } } }
internal Task <IRandomAccessStreamWithContentType> Open(CancellationToken ct, FileAccessMode accessMode, StorageOpenOptions options) => _impl.Open(ct, accessMode, options);
private Task<IRandomAccessStream> OpenStreamAsync(TorrentFile file, FileAccessMode access, AsynTokens asynTokens) { return Task.Run(async () => { var token = asynTokens.CancellationTokenSource.Token; var fullPath = file.FullPath; var storageFile = await StorageHelper.CreateFileAsync(fullPath, file.TargetFolder); if (access == FileAccessMode.ReadWrite) { var stream = File.Open(storageFile.Path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); var randomAccessStream = stream.AsRandomAccessStream(); try { var size = (long) randomAccessStream.Size; var length = file.Length - size; if (length > 0L) { var buffer = ClientEngine.BufferManager.GetBuffer((int) Math.Min(length, 524288L)); try { randomAccessStream.Seek((ulong) size); for (var i = size; i < file.Length; i = i + (long) buffer.Length) { length = length - await randomAccessStream.WriteAsync( buffer.AsBuffer(0, (int) Math.Min(length, buffer.Length))); token.ThrowIfCancellationRequested(); } } finally { ClientEngine.BufferManager.FreeBuffer(ref buffer); } } } finally { randomAccessStream?.Dispose(); } } return await storageFile.OpenAsync(access); }); }
internal Task <Stream> OpenStream(CancellationToken ct, FileAccessMode accessMode, StorageOpenOptions options) => _impl.OpenStream(ct, accessMode, options);
unsafe void convert_filename(byte* srcname, byte* destname, ref FileAccessMode filemode, ref FileType filetype, ref bool wildflag) { byte* p, q; // Search for ':', p points to first character after ':' if ((p = CharFunctions.strchr(srcname, ':')) != null) p++; else p = srcname; // Convert char set of the remaining string -> destname q = destname; for (int i = 0; i < IEC.NAMEBUF_LENGTH && (*q++ = conv_from_64(*p++, true)) != 0; i++) ; // Look for mode parameters seperated by ',' p = destname; while ((p = CharFunctions.strchr(p, ',')) != null) { // Cut string after the first ',' *p++ = 0; switch ((Char)(*p)) { case 'p': filetype = FileType.FTYPE_PRG; break; case 's': filetype = FileType.FTYPE_SEQ; break; case 'r': filemode = FileAccessMode.FMODE_READ; break; case 'w': filemode = FileAccessMode.FMODE_WRITE; break; case 'a': filemode = FileAccessMode.FMODE_APPEND; break; } } // Search for wildcards wildflag = CharFunctions.strchr(destname, '?') != null || CharFunctions.strchr(destname, '*') != null; }
public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions) { var defaultBufferSize = 4096; return(new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), defaultBufferSize, GetFileOptions(fileOpenOptions))); }
public IAsyncOperation<IRandomAccessStream> OpenAsync(FileAccessMode accessMode) { throw new NotImplementedException(); }
/// <summary> /// Initializes a new instance of the <see cref="DatabaseReader" /> class. /// </summary> /// <param name="file">The MaxMind DB file.</param> /// <param name="mode">The mode by which to access the DB file.</param> public DatabaseReader(string file, FileAccessMode mode = FileAccessMode.MemoryMapped) : this(file, new List <string> { "en" }, mode) { }
public Windows.Foundation.IAsyncOperation<Windows.Storage.Streams.IRandomAccessStream> OpenAsync(FileAccessMode accessMode) { throw new NotImplementedException(); }
/// <summary> /// Initializes a new instance of the <see cref="DatabaseReader" /> class. /// </summary> /// <param name="file">The MaxMind DB file.</param> /// <param name="locales">List of locale codes to use in name property from most preferred to least preferred.</param> /// <param name="mode">The mode by which to access the DB file.</param> public DatabaseReader(string file, IEnumerable <string> locales, FileAccessMode mode = FileAccessMode.MemoryMapped) { _locales = new List <string>(locales); _reader = new Reader(file, mode); }
public override Stream Open(FilePath file, FileAccessMode accessMode) { switch (accessMode) { case FileAccessMode.Read: return File.Open(PathToRealPath(file), FileMode.Open, FileAccess.Read); case FileAccessMode.Write: return File.Open(PathToRealPath(file), FileMode.OpenOrCreate, FileAccess.Write); case FileAccessMode.ReadWrite: return File.Open(PathToRealPath(file), FileMode.OpenOrCreate, FileAccess.ReadWrite); default: throw new ArgumentException("Impossible value for accessMode."); } }
private async Task <FileStreamBase> OpenAsync(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { // Win32 CreateFile returns ERROR_PATH_NOT_FOUND when given a path that ends with '\' if (PathHelpers.EndsInDirectorySeparator(fullPath)) { throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, fullPath); } StorageFile file = null; // FileMode if (mode == FileMode.Open || mode == FileMode.Truncate) { file = await StorageFile.GetFileFromPathAsync(fullPath).TranslateWinRTTask(fullPath); } else { CreationCollisionOption collisionOptions; switch (mode) { case FileMode.Create: collisionOptions = CreationCollisionOption.ReplaceExisting; break; case FileMode.CreateNew: collisionOptions = CreationCollisionOption.FailIfExists; break; case FileMode.Append: case FileMode.OpenOrCreate: default: collisionOptions = CreationCollisionOption.OpenIfExists; break; } string directoryPath, fileName; PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName); StorageFolder directory = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true); file = await directory.CreateFileAsync(fileName, collisionOptions).TranslateWinRTTask(fullPath); } // FileAccess: WinRT doesn't support FileAccessMode.Write so we upgrade to ReadWrite FileAccessMode accessMode = ((access & FileAccess.Write) != 0) ? FileAccessMode.ReadWrite : FileAccessMode.Read; // FileShare: cannot translate StorageFile uses a different sharing model (oplocks) that is controlled via FileAccessMode // FileOptions: ignore most values of FileOptions as they are hints and are not supported by WinRT. // FileOptions.Encrypted is not a hint, and not supported by WinRT, but there is precedent for ignoring this (FAT). // FileOptions.DeleteOnClose should result in an UnauthorizedAccessException when // opening a file that can only be read, but we cannot safely reproduce that behavior // in WinRT without actually deleting the file. // Instead the failure will occur in the finalizer for WinRTFileStream and be ignored. // open our stream Stream stream = (await file.OpenAsync(accessMode).TranslateWinRTTask(fullPath)).AsStream(bufferSize); if (mode == FileMode.Append) { // seek to end. stream.Seek(0, SeekOrigin.End); } else if (mode == FileMode.Truncate) { // truncate stream to 0 stream.SetLength(0); } return(new WinRTFileStream(stream, file, access, options, parent)); }