System.IO.File.OpenRead(string)

Here are the examples of the csharp api System.IO.File.OpenRead(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3921 Examples 7

19 Source : EdisFace.cs
with MIT License
from 0ffffffffh

private bool ReplyWithFile(HttpListenerContext ctx, string fileName)
        {
            Stream fs;

            if (!File.Exists(fileName))
                return false;

            try
            {
                fs = File.OpenRead(fileName);
            }
            catch(Exception e)
            {
                Log.Error("{0} - {1}", fileName, e.Message);
                return false;
            }

            ctx.Response.ContentLength64 = fs.Length;
            ctx.Response.StatusCode = 200;

            ctx.Response.ContentEncoding = Encoding.ASCII;
            ctx.Response.ContentType = MimeTypeFromExt(Path.GetExtension(fileName));

            fs.CopyTo(ctx.Response.OutputStream);

            fs.Close();
            fs.Dispose();

            return true;
        }

19 Source : CelesteNetServerModule.cs
with MIT License
from 0x0ade

public virtual void Load(string path = "") {
            FilePath = path = Path.GetFullPath(path.Nullify() ?? FilePath);

            if (!File.Exists(path)) {
                Save(path);
                return;
            }

            Logger.Log(LogLevel.INF, "settings", $"Loading {GetType().Name} from {path}");

            using Stream stream = File.OpenRead(path);
            using StreamReader reader = new(stream);
            Load(reader);
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public bool TryLoadRaw<T>(string path, out T value) where T : new() {
            lock (GlobalLock) {
                if (!File.Exists(path)) {
                    value = new();
                    return false;
                }

                using Stream stream = File.OpenRead(path);
                using StreamReader reader = new(stream);
                value = YamlHelper.Deserializer.Deserialize<T>(reader) ?? new();
                return true;
            }
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public override Stream? ReadFile(string uid, string name) {
            string path = GetUserFilePath(uid, name);
            if (!File.Exists(path))
                return null;
            return File.OpenRead(path);
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public override void CopyTo(UserData other) {
            using UserDataBatchContext batch = other.OpenBatch();
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);

                Dictionary<string, Type?> types = new();
                replacedembly[] asms = AppDomain.CurrentDomain.Getreplacedemblies();

                foreach (string uid in GetAll()) {
                    PrivateUserInfo info = Load<PrivateUserInfo>(uid);
                    other.Insert(uid, info.Key, info.KeyFull, !info.KeyFull.IsNullOrEmpty());

                    foreach (string path in Directory.GetFiles(Path.Combine(UserRoot, uid))) {
                        string name = Path.GetFileNameWithoutExtension(path);
                        if (name == typeof(PrivateUserInfo).FullName)
                            continue;

                        if (!types.TryGetValue(name, out Type? type)) {
                            foreach (replacedembly asm in asms)
                                if ((type = asm.GetType(name)) != null)
                                    break;
                            types[name] = type;
                        }

                        using Stream stream = File.OpenRead(path);
                        other.InsertData(uid, name, type, stream);
                    }

                    string dir = Path.Combine(UserRoot, uid, "data");
                    if (Directory.Exists(dir)) {
                        foreach (string path in Directory.GetFiles(dir)) {
                            string name = Path.GetFileName(path);
                            using Stream stream = File.OpenRead(path);
                            other.InsertFile(uid, name, stream);
                        }
                    }
                }
            }
        }

19 Source : Ribbon.cs
with GNU General Public License v3.0
from 0dteam

static string CalculateMD5(string filename)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = File.OpenRead(filename))
                {
                    var hash = md5.ComputeHash(stream);
                    return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
                }
            }
        }

19 Source : Ribbon.cs
with GNU General Public License v3.0
from 0dteam

private string GetHashSha256(string filename)
        {
            using (FileStream stream = File.OpenRead(filename))
            {
                SHA256Managed sha = new SHA256Managed();
                byte[] shaHash = sha.ComputeHash(stream);
                string result = "";
                foreach (byte b in shaHash) result += b.ToString("x2");
                return result;
            }
        }

19 Source : Frontend.cs
with MIT License
from 0x0ade

public Stream? OpenContent(string path, out string pathNew, out DateTime? lastMod, out string? contentType) {
            pathNew = path;

            try {
                string dir = Path.GetFullPath(Settings.ContentRoot);
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }

#if DEBUG
            try {
                string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "Content"));
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }

            try {
                string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "CelesteNet.Server.FrontendModule", "Content"));
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }
#endif

            if (!path.EndsWith("/index.html")) {
                path = path.EndsWith("/") ? path : (path + "/");
                Stream? index = OpenContent(path + "index.html", out _, out lastMod, out contentType);
                if (index != null) {
                    pathNew = path;
                    return index;
                }
            }

            lastMod = null;
            contentType = GetContentType(path);
            return typeof(CelesteNetServer).replacedembly.GetManifestResourceStream("Celeste.Mod.CelesteNet.Server.Content." + path.Replace("/", "."));
        }

19 Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

19 Source : LocalStorageHandler.cs
with Apache License 2.0
from 0xFireball

public Stream RetrieveFileStream(string id)
        {
            // Quota is not affected
            var filePath = GetTargetFilePath(id);
            return File.OpenRead(filePath);
        }

19 Source : Log4NetProvider.cs
with MIT License
from 1100100

private static XmlElement ReadConfigFile(string filename)
        {
            if (XmlElement != null)
                return XmlElement;
            var log4NetConfig = new XmlDoreplacedent();
            using (var stream = File.OpenRead(filename))
            {
                log4NetConfig.Load(stream);
                return XmlElement = log4NetConfig["log4net"];
            }
        }

19 Source : Extensions.cs
with MIT License
from 5minlab

public static void WriteFile(this HttpListenerResponse response, string path, string type = "application/octet-stream", bool download = false) {
            using (FileStream fs = File.OpenRead(path)) {
                response.StatusCode = (int)HttpStatusCode.OK;
                response.StatusDescription = "OK";
                response.ContentLength64 = fs.Length;
                response.ContentType = type;
                if (download)
                    response.AddHeader("Content-disposition", string.Format("attachment; filename={0}", Path.GetFileName(path)));

                byte[] buffer = new byte[64 * 1024];
                int read;
                while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) {
                    // FIXME required?
                    System.Threading.Thread.Sleep(0);
                    response.OutputStream.Write(buffer, 0, read);
                }
            }
        }

19 Source : AssemblyLoading.cs
with MIT License
from 71

[MethodImpl(MethodImplOptions.NoInlining)]
        private static replacedembly LoadCore(replacedemblyLoadContext ctx, string path)
        {
            using (FileStream fs = File.OpenRead(path))
            {
                // Load from a stream instead of loading from path, in order
                // to avoid locking the file.
                string pdbFile = Path.ChangeExtension(path, ".pdb");

                if (!File.Exists(pdbFile))
                    return ctx.LoadFromStream(fs);

                FileStream pdbFs = null;

                try
                {
                    pdbFs = File.OpenRead(pdbFile);

                    return ctx.LoadFromStream(fs, pdbFs);
                }
                catch
                {
                    return ctx.LoadFromStream(fs);
                }
                finally
                {
                    pdbFs?.Dispose();
                }
            }
        }

19 Source : LyricsFetcher.cs
with MIT License
from 71

public static bool GetLocalLyrics(string songId, List<Subreplacedle> subreplacedles)
        {
            string songDirectory = Loader.CustomLevels.Values.FirstOrDefault(x => x.levelID == songId)?.customLevelPath;

            Debug.Log($"[Beat Singer] Song directory: {songDirectory}.");

            if (songDirectory == null)
                return false;

            // Find JSON lyrics
            string jsonFile = Path.Combine(songDirectory, "lyrics.json");

            if (File.Exists(jsonFile))
            {
                PopulateFromJson(File.ReadAllText(jsonFile), subreplacedles);

                return true;
            }

            // Find SRT lyrics
            string srtFile = Path.Combine(songDirectory, "lyrics.srt");

            if (File.Exists(srtFile))
            {
                using (FileStream fs = File.OpenRead(srtFile))
                using (StreamReader reader = new StreamReader(fs))
                {
                    PopulateFromSrt(reader, subreplacedles);

                    return true;
                }

            }

            return false;
        }

19 Source : SimpleJSON.cs
with MIT License
from 734843327

public static JSONNode LoadFromFile(string aFileName)
		{
			using(var F = System.IO.File.OpenRead(aFileName))
			{
				return LoadFromStream(F);
			}
		}

19 Source : DecorationMaster.cs
with GNU General Public License v3.0
from a2659802

public override string GetVersion()
        {
            replacedembly asm = replacedembly.GetExecutingreplacedembly();

            string ver = Version.ToString("0.000");

            using SHA1 sha1 = SHA1.Create();
            using FileStream stream = File.OpenRead(asm.Location);

            byte[] hashBytes = sha1.ComputeHash(stream);

            string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();

            return $"{ver}-{hash.Substring(0, 6)}";
        }

19 Source : SerializeHelper.cs
with GNU General Public License v3.0
from a2659802

public static T LoadGlobalSettings<T>()
        {
            var _globalSettingsPath = GLOBAL_FILE_DIR;
            if (!File.Exists(_globalSettingsPath))
                return default;

            Log("Loading Global Settings");

            using (FileStream fileStream = File.OpenRead(_globalSettingsPath))
            {
                using (var reader = new StreamReader(fileStream))
                {
                    string json = reader.ReadToEnd();
                    Type settingsType = typeof(T);
                    T settings = default;

                    try
                    {
                        settings = (T)JsonConvert.DeserializeObject(
                            json,
                            settingsType,
                            new JsonSerializerSettings
                            {
                                TypeNameHandling = TypeNameHandling.Auto,
                            }
                        );
                    }
                    catch (Exception e)
                    {
                        LogError("Failed to load settings using Json.Net.");
                        LogError(e);
                    }

                    return settings;
                }
            }
        }

19 Source : SerializeHelper.cs
with GNU General Public License v3.0
from a2659802

public static T LoadSceneSettings<T>(string sceneName)
        {
            string dir = Path.Combine(DATA_DIR, sceneName + ".json");
            if (!File.Exists(dir))
                return default;

            Log($"Loading {sceneName} Settings");

            using (FileStream fileStream = File.OpenRead(dir))
            {
                using (var reader = new StreamReader(fileStream))
                {
                    string json = reader.ReadToEnd();
                    Type settingsType = typeof(T);
                    T settings = default;

                    try
                    {
                        settings = (T)JsonConvert.DeserializeObject(
                            json,
                            settingsType,
                            new JsonSerializerSettings
                            {
                                TypeNameHandling = TypeNameHandling.Auto,
                            }
                        );
                    }
                    catch (Exception e)
                    {
                        LogError("Failed to load settings using Json.Net.");
                        LogError(e);
                    }

                    return settings;
                }
            }
        }

19 Source : Program.cs
with Apache License 2.0
from AantCoder

static void Main(string[] args)
        {
            var workPort = args == null || args.Length < 2 ? 0 : int.Parse(args[1]);
            var workPath = @"C:\World" + (workPort == 0 ? "" : "\\" + workPort.ToString());

            var SaveFileName = Path.Combine(workPath, "World.dat");
            var SaveFileNameOld = Path.Combine(workPath, "WorldOld.dat");
    
            if (!File.Exists(SaveFileName)) 
            {
                return;
            }

            File.Copy(SaveFileName, SaveFileNameOld, true);

            BaseContainer Data;
            using (var fs = File.OpenRead(SaveFileName))
            {
                var bf = new BinaryFormatter();
                Data = (BaseContainer)bf.Deserialize(fs);
            }

            //тут будет код конвертации, если понадобиться


            using (var fs = File.OpenWrite(SaveFileName))
            {
                var bf = new BinaryFormatter();
                bf.Serialize(fs, Data);
            }
        }

19 Source : RepositorySaveData.cs
with Apache License 2.0
from AantCoder

public byte[] LoadPlayerData(string login, int numberSave)
        {
            if (numberSave < 1 || numberSave > CountSaveDataPlayer) return null;

            var fileName = GetFileNameBase(login) + numberSave.ToString();

            var info = new FileInfo(fileName);
            if (!info.Exists || info.Length < 10) return null;

            //читаем содержимое
            bool readAsXml;
            using (var file = File.OpenRead(fileName))
            {
                var buff = new byte[10];
                file.Read(buff, 0, 10);
                readAsXml = Encoding.ASCII.GetString(buff, 0, 10).Contains("<?xml");
            }
            //считываем текст как xml сейва или как сжатого zip'а
            var saveFileData = File.ReadAllBytes(fileName);
            if (readAsXml)
            {
                return saveFileData;
            }
            else
            {
                return GZip.UnzipByteByte(saveFileData);
            }
        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public void Load()
        {
            bool needResave = false;
            if (!Directory.Exists(SaveFolderDataPlayers))
                Directory.CreateDirectory(SaveFolderDataPlayers);
            if (!File.Exists(SaveFileName))
            {
                Data = new BaseContainer();
                Save();
                Loger.Log("Server Create Data");
            }
            else
            {
                using (var fs = File.OpenRead(SaveFileName))
                {
                    var bf = new BinaryFormatter() { Binder = new ServerCoreSerializationBinder() };
                    Loger.Log("Server Load...");
                    Data = (BaseContainer)bf.Deserialize(fs);
                    //var dataVersion = Data.VersionNum;
                    Loger.Log("Server Version data: " + Data.Version + " Current version: " + MainHelper.VersionInfo);

                    if (Data.Version != MainHelper.VersionInfo || Data.VersionNum < MainHelper.VersionNum + 1)
                    {
                        convertToLastVersion();
                        needResave = true;
                    }

                    if (Data.Orders == null) Data.Orders = new List<OrderTrade>();

                    Data.UpdatePlayersAllDic();

                    Loger.Log("Server Load done. Users " + Data.PlayersAll.Count.ToString() + ": "
                        + Data.PlayersAll.Select(p => p.Public.Login).Aggregate((string)null, (r, i) => (r == null ? "" : r + ", ") + i)
                        );

                    ChatManager.Instance.NewChatManager(Data.MaxIdChat, Data.PlayerSystem.Chats.Keys.First());
                }
            }


            if (needResave)
                Save();
            ChangeData = false;


        }

19 Source : ResourceController.cs
with MIT License
from Abdulrhman5

[Route("Photo/{type}/{name}")]
        public async Task<IActionResult> Photo([FromRoute]string type, [FromRoute]string name)
        {
            if (type.EqualsIC("Profile"))
            {
                var profilePhotoPath = $@"{_contentRoot}\replacedets\Images\Profile\";
                var files = Directory.GetFiles(profilePhotoPath, $"{name}.*");
                if (!files.Any())
                {
                    return StatusCode(new ErrorMessage
                    {
                        StatusCode = System.Net.HttpStatusCode.NotFound,
                        ErrorCode = "RESOURCE.PHOTO.NOT.FOUND",
                        Message = "The image you requested does not exists"
                    });
                }
                else
                {
                    var file = System.IO.File.OpenRead(files.FirstOrDefault());
                    return File(file, "Image/jpeg");
                }
            }
            else
            {
                return StatusCode(new ErrorMessage
                {
                    StatusCode = System.Net.HttpStatusCode.NotFound,
                    ErrorCode = "RESOURCE.PHOTO.TYPE.NOT.FOUND",
                    Message = "The file you requested does not exists"
                });
            }
        }

19 Source : ResourceController.cs
with MIT License
from Abdulrhman5

[Route("Photo/{type}/{name}")]
        public async Task<IActionResult> Photo([FromRoute]string type, [FromRoute]string name)
        {
            if (type.EqualsIC("Tag") || type.EqualsIC("Object"))
            {
                var profilePhotoPath = $@"{_contentRoot}\replacedets\Images\Profile\";
                var files = Directory.GetFiles(profilePhotoPath, $"{name}.*");
                if (!files.Any())
                {
                    return StatusCode(new ErrorMessage
                    {
                        StatusCode = System.Net.HttpStatusCode.NotFound,
                        ErrorCode = "RESOURCE.PHOTO.NOT.FOUND",
                        Message = "The image you requested does not exists"
                    });
                }
                else
                {
                    var file = System.IO.File.OpenRead(files.FirstOrDefault());
                    return File(file, "Image/jpeg");
                }
            }
            else
            {
                return StatusCode(new ErrorMessage
                {
                    StatusCode = System.Net.HttpStatusCode.NotFound,
                    ErrorCode = "RESOURCE.PHOTO.TYPE.NOT.FOUND",
                    Message = "The file you requested does not exists"
                });
            }
        }

19 Source : AutomationTestBase.cs
with MIT License
from ABTSoftware

public WriteableBitmap LoadFromPng(string fileName)
        {
            WriteableBitmap bmp;

            using (var fileStream = File.OpenRead(fileName))
            {
                bmp = DecodePngStream(fileStream);
            }

            return bmp;
        }

19 Source : LocalBlogService.cs
with Apache License 2.0
from acblog

public async Task<BlogOptions> GetOptions(CancellationToken cancellationToken = default)
        {
            string path = Path.Join(RootPath, Workspace.BlogOptionPath);
            if (System.IO.File.Exists(path))
            {
                await using var st = System.IO.File.OpenRead(path);
                return
                    await JsonSerializer.DeserializeAsync<BlogOptions>(st, cancellationToken: cancellationToken).ConfigureAwait(false)
                    ?? throw new NullReferenceException("Options is null");
            }
            else
            {
                return new BlogOptions();
            }
        }

19 Source : RecordFSRepo.cs
with Apache License 2.0
from acblog

public override async Task<T?> Get(string id, CancellationToken cancellationToken = default)
        {
            string path = GetPath(id);
            await using var fs = System.IO.File.OpenRead(path);
            using var sr = new StreamReader(fs);
            var src = await sr.ReadToEndAsync().ConfigureAwait(false);
            var (metadata, content) = ObjectTextual.Parse<TMeta>(src);

            return await CreateExistedItem(id, metadata, content).ConfigureAwait(false);
        }

19 Source : Program.cs
with MIT License
from acid-chicken

public static async Task<Config> LoadConfigAsync(string path = ConfigurePath)
        {
            Config result;
            try
            {
                using (var stream = File.OpenRead(path))
                using (var reader = new StreamReader(stream))
                {
                    result = JsonConvert.DeserializeObject<Config>(await reader.ReadToEndAsync().ConfigureAwait(false));
                    await RequestLogAsync(new LogMessage(LogSeverity.Verbose, "Program", "The config has been loaded successfully.")).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                await RequestLogAsync(new LogMessage(LogSeverity.Error, "Program", ex.Message, ex)).ConfigureAwait(false);
                throw;
            }
            return result;
        }

19 Source : DeploymentManager.cs
with MIT License
from action-bi-toolkit

internal static async Task DeployReportAsync(PbiDeploymentManifest manifest, string label, string environment)
        { 
            if (!manifest.Environments.ContainsKey(environment))
                throw new DeploymentException($"The manifest does not contain the specified environment: {environment}.");

            var deploymentEnv = manifest.Environments[environment];

            if (deploymentEnv.Disabled)
            {
                Log.Warning("Deployment environment '{Environment}' disabled. Aborting.", environment);
                return;
            }

            Log.Information("Starting deployment '{DeploymentLabel}' into environment: {Environment}...", label, environment);

            // Build PBIX

            var tempDir = Environment.ExpandEnvironmentVariables(String.IsNullOrEmpty(manifest.Options.TempDir) ? "%TEMP%" : manifest.Options.TempDir);
            Log.Debug("Using TEMP dir: {TempDir}", tempDir);
            var reportPath = Path.Combine(tempDir, $"{new DirectoryInfo(manifest.Source.Path).Name}.pbix");
            Log.Debug("Creating PBIX from report source at: '{Path}'...", reportPath);

            var model = PbixModel.FromFolder(manifest.Source.Path);

            model.ToFile(reportPath, PowerBI.PbiFileFormat.PBIX);

            // Get auth token

            var app = ConfidentialClientApplicationBuilder
                .Create(Environment.ExpandEnvironmentVariables(manifest.Authentication.ClientId))
                .WithClientSecret(Environment.ExpandEnvironmentVariables(manifest.Authentication.ClientSecret))
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{Environment.ExpandEnvironmentVariables(manifest.Authentication.TenantId)}"))
                // TODO Support custom authority
                .Build();

            string[] scopes = new string[] { $"{POWERBI_API_RESOURCE}/.default" };

            AuthenticationResult result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            var tokenCredentials = new TokenCredentials(result.AccessToken, result.TokenType);
            Log.Information("Access token received. Expires On: {ExpiresOn}", result.ExpiresOn);

            // Use Power BI API to import PBIX

            using (var powerbi = new PowerBIClient(DefaultPowerBIApiBaseUri, tokenCredentials))
            { 
                Import import;
                using (var file = File.OpenRead(reportPath))
                {
                    import = await powerbi.Imports.PostImportWithFileAsyncInGroup(deploymentEnv.WorkspaceId, file,
                        datasetDisplayName: Path.GetFileName(reportPath), // will FAIL without the parameter (although the API marks it as optional)
                        nameConflict: manifest.Options.NameConflict
                    );
                }

                while (import.ImportState != "Succeeded") // Must use magic string here :(
                {
                    if (import.ImportState != null)
                        Log.Information("Import: {Name}, State: {ImportState} (Id: {Id})", import.Name, import.ImportState, import.Id);

                    if (import.ImportState == "Failed")
                        throw new DeploymentException($"Deployment '{import.Name}' ({import.Id}) failed.");

                    await Task.Delay(500);

                    import = await powerbi.Imports.GetImportInGroupAsync(deploymentEnv.WorkspaceId, import.Id);
                }

                Log.Information("Import succeeded: {Id} ({Name})\n\tReport: {ReportId} \"{ReportName}\"\n\tUrl: {WebUrl}"
                    , import.Id
                    , import.Name
                    , import.Reports[0].Id
                    , import.Reports[0].Name
                    , import.Reports[0].WebUrl
                );
                Log.Information("Report Created: {Created}", import.CreatedDateTime);
                Log.Information("Report Updated: {Updated}", import.UpdatedDateTime);
            }
        }

19 Source : ProjectFile.cs
with MIT License
from action-bi-toolkit

public bool TryReadFile(out Stream stream)
        {
            Log.Verbose("Attempting to read file: {Path}", Path);
            if (File.Exists(Path))
            {
                stream = File.OpenRead(Path);
                Log.Debug("File successfully opened: {Path}", Path);
                return true;
            }

            Log.Debug("File not found: {Path}", Path);
            stream = null;
            return false;
        }

19 Source : ProjectFolder.cs
with MIT License
from action-bi-toolkit

public bool TryReadFile(string path, Action<Stream> streamHandler)
        {
            var fullPath = GetFullPath(path);
            Log.Verbose("Attempting to read file: {Path}", fullPath);
            if (File.Exists(fullPath))
            {
                using (var stream = File.OpenRead(fullPath))
                {
                    streamHandler(stream);
                }
                Log.Debug("Successfully read file: {Path}", fullPath);
                return true;
            }
            else
            {
                Log.Debug("File not found: {Path}", fullPath);
                return false;
            }
        }

19 Source : SelfUpdater.cs
with MIT License
from actions

private async Task DownloadLatestRunner(CancellationToken token)
        {
            string latestRunnerDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Path.UpdateDirectory);
            IOUtil.DeleteDirectory(latestRunnerDirectory, token);
            Directory.CreateDirectory(latestRunnerDirectory);

            int runnerSuffix = 1;
            string archiveFile = null;
            bool downloadSucceeded = false;

            try
            {
                // Download the runner, using multiple attempts in order to be resilient against any networking/CDN issues
                for (int attempt = 1; attempt <= Constants.RunnerDownloadRetryMaxAttempts; attempt++)
                {
                    // Generate an available package name, and do our best effort to clean up stale local zip files
                    while (true)
                    {
                        if (_targetPackage.Platform.StartsWith("win"))
                        {
                            archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.zip");
                        }
                        else
                        {
                            archiveFile = Path.Combine(latestRunnerDirectory, $"runner{runnerSuffix}.tar.gz");
                        }

                        try
                        {
                            // delete .zip file
                            if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
                            {
                                Trace.Verbose("Deleting latest runner package zip '{0}'", archiveFile);
                                IOUtil.DeleteFile(archiveFile);
                            }

                            break;
                        }
                        catch (Exception ex)
                        {
                            // couldn't delete the file for whatever reason, so generate another name
                            Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
                            runnerSuffix++;
                        }
                    }

                    // Allow a 15-minute package download timeout, which is good enough to update the runner from a 1 Mbit/s ADSL connection.
                    if (!int.TryParse(Environment.GetEnvironmentVariable("GITHUB_ACTIONS_RUNNER_DOWNLOAD_TIMEOUT") ?? string.Empty, out int timeoutSeconds))
                    {
                        timeoutSeconds = 15 * 60;
                    }

                    Trace.Info($"Attempt {attempt}: save latest runner into {archiveFile}.");

                    using (var downloadTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds)))
                    using (var downloadCts = CancellationTokenSource.CreateLinkedTokenSource(downloadTimeout.Token, token))
                    {
                        try
                        {
                            Trace.Info($"Download runner: begin download");

                            //open zip stream in async mode
                            using (HttpClient httpClient = new HttpClient(HostContext.CreateHttpClientHandler()))
                            {
                                if (!string.IsNullOrEmpty(_targetPackage.Token))
                                {
                                    Trace.Info($"Adding authorization token ({_targetPackage.Token.Length} chars)");
                                    httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _targetPackage.Token);
                                }

                                Trace.Info($"Downloading {_targetPackage.DownloadUrl}");

                                using (FileStream fs = new FileStream(archiveFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
                                using (Stream result = await httpClient.GetStreamAsync(_targetPackage.DownloadUrl))
                                {
                                    //81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).
                                    await result.CopyToAsync(fs, 81920, downloadCts.Token);
                                    await fs.FlushAsync(downloadCts.Token);
                                }
                            }

                            Trace.Info($"Download runner: finished download");
                            downloadSucceeded = true;
                            break;
                        }
                        catch (OperationCanceledException) when (token.IsCancellationRequested)
                        {
                            Trace.Info($"Runner download has been canceled.");
                            throw;
                        }
                        catch (Exception ex)
                        {
                            if (downloadCts.Token.IsCancellationRequested)
                            {
                                Trace.Warning($"Runner download has timed out after {timeoutSeconds} seconds");
                            }

                            Trace.Warning($"Failed to get package '{archiveFile}' from '{_targetPackage.DownloadUrl}'. Exception {ex}");
                        }
                    }
                }

                if (!downloadSucceeded)
                {
                    throw new TaskCanceledException($"Runner package '{archiveFile}' failed after {Constants.RunnerDownloadRetryMaxAttempts} download attempts");
                }

                // If we got this far, we know that we've successfully downloaded the runner package
                // Validate Hash Matches if it is provided
                using (FileStream stream = File.OpenRead(archiveFile))
                {
                    if (!String.IsNullOrEmpty(_targetPackage.HashValue))
                    {
                        using (SHA256 sha256 = SHA256.Create())
                        {
                            byte[] srcHashBytes = await sha256.ComputeHashAsync(stream);
                            var hash = PrimitiveExtensions.ConvertToHexString(srcHashBytes);
                            if (hash != _targetPackage.HashValue)
                            {
                                // Hash did not match, we can't recover from this, just throw
                                throw new Exception($"Computed runner hash {hash} did not match expected Runner Hash {_targetPackage.HashValue} for {_targetPackage.Filename}");
                            }
                            Trace.Info($"Validated Runner Hash matches {_targetPackage.Filename} : {_targetPackage.HashValue}");
                        }
                    }
                }
                if (archiveFile.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                {
                    ZipFile.ExtractToDirectory(archiveFile, latestRunnerDirectory);
                }
                else if (archiveFile.EndsWith(".tar.gz", StringComparison.OrdinalIgnoreCase))
                {
                    string tar = WhichUtil.Which("tar", trace: Trace);

                    if (string.IsNullOrEmpty(tar))
                    {
                        throw new NotSupportedException($"tar -xzf");
                    }

                    // tar -xzf
                    using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
                    {
                        processInvoker.OutputDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                        {
                            if (!string.IsNullOrEmpty(args.Data))
                            {
                                Trace.Info(args.Data);
                            }
                        });

                        processInvoker.ErrorDataReceived += new EventHandler<ProcessDataReceivedEventArgs>((sender, args) =>
                        {
                            if (!string.IsNullOrEmpty(args.Data))
                            {
                                Trace.Error(args.Data);
                            }
                        });

                        int exitCode = await processInvoker.ExecuteAsync(latestRunnerDirectory, tar, $"-xzf \"{archiveFile}\"", null, token);
                        if (exitCode != 0)
                        {
                            throw new NotSupportedException($"Can't use 'tar -xzf' extract archive file: {archiveFile}. return code: {exitCode}.");
                        }
                    }
                }
                else
                {
                    throw new NotSupportedException($"{archiveFile}");
                }

                Trace.Info($"Finished getting latest runner package at: {latestRunnerDirectory}.");
            }
            finally
            {
                try
                {
                    // delete .zip file
                    if (!string.IsNullOrEmpty(archiveFile) && File.Exists(archiveFile))
                    {
                        Trace.Verbose("Deleting latest runner package zip: {0}", archiveFile);
                        IOUtil.DeleteFile(archiveFile);
                    }
                }
                catch (Exception ex)
                {
                    //it is not critical if we fail to delete the .zip file
                    Trace.Warning("Failed to delete runner package zip '{0}'. Exception: {1}", archiveFile, ex);
                }
            }

            // copy latest runner into runner root folder
            // copy bin from _work/_update -> bin.version under root
            string binVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.BinDirectory}.{_targetPackage.Version}");
            Directory.CreateDirectory(binVersionDir);
            Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory)} to {binVersionDir}.");
            IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.BinDirectory), binVersionDir, token);

            // copy externals from _work/_update -> externals.version under root
            string externalsVersionDir = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), $"{Constants.Path.ExternalsDirectory}.{_targetPackage.Version}");
            Directory.CreateDirectory(externalsVersionDir);
            Trace.Info($"Copy {Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory)} to {externalsVersionDir}.");
            IOUtil.CopyDirectory(Path.Combine(latestRunnerDirectory, Constants.Path.ExternalsDirectory), externalsVersionDir, token);

            // copy and replace all .sh/.cmd files
            Trace.Info($"Copy any remaining .sh/.cmd files into runner root.");
            foreach (FileInfo file in new DirectoryInfo(latestRunnerDirectory).GetFiles() ?? new FileInfo[0])
            {
                string destination = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Root), file.Name);

                // Removing the file instead of just trying to overwrite it works around permissions issues on linux.
                // https://github.com/actions/runner/issues/981
                Trace.Info($"Copy {file.FullName} to {destination}");
                IOUtil.DeleteFile(destination);
                file.CopyTo(destination, true);
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

internal static async Task<OcrResult> UploadAndRecognizeImageAsync(string imageFilePath, OcrLanguages language)
        {
            string key = "Key";
            string endPoint = "https://tasmu-ocr-solution.cognitiveservices.azure.com/";
            var credentials = new ApiKeyServiceClientCredentials(key);

            using (var client = new ComputerVisionClient(credentials) { Endpoint = endPoint })
            {
                using (Stream imageFileStream = File.OpenRead(imageFilePath))
                {
                    OcrResult ocrResult = await client.RecognizePrintedTextInStreamAsync(false, imageFileStream, language);

                    return ocrResult;
                }
            }
        }

19 Source : PersistSequentialModel.cs
with MIT License
from adamtiger

public static SequentialModel DeserializeModel(string fileName)
        {
            SequentialModel model = null;
            if (File.Exists(fileName))
            {
                Stream stream = File.OpenRead(fileName);
                BinaryFormatter deserializer = new BinaryFormatter();
                model = (SequentialModel)deserializer.Deserialize(stream);
                stream.Close();
            }
            else
                throw new Exception("Trying to serialize a non-existing file.");

            return model;
        }

19 Source : RealXamlPacakge.cs
with MIT License
from admaiorastudio

private async void BuildEvents_OnBuildDone(vsBuildScope Scope, vsBuildAction Action)
        {
            if (!UpdateManager.Current.IsConnected)
                return;

            try
            {
                await this.JoinableTaskFactory.SwitchToMainThreadAsync(this.DisposalToken);
                if (_mainDllProject != null
                    && Scope == vsBuildScope.vsBuildScopeProject
                    && Action == vsBuildAction.vsBuildActionBuild)
                {
                    EnvDTE.Property property = _mainDllProject.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath");
                    string fullPath = _mainDllProject.Properties.Item("FullPath").Value.ToString();
                    string outputFileName = _mainDllProject.Properties.Item("OutputFileName").Value.ToString();
                    string outputPath = property.Value.ToString();

                    string replacedemblyPath = Path.Combine(fullPath, outputPath, outputFileName);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        // Make a copy of the file into memory to avoid any file lock                   
                        using (FileStream fs = File.OpenRead(replacedemblyPath))
                            await fs.CopyToAsync(ms);

                        await UpdateManager.Current.SendreplacedemblyAsync(outputFileName, ms.ToArray());

                        if(_xamlCache.Count > 0)
                        {
                            // Force a xaml update for every page
                            foreach(var cacheItem in _xamlCache)                            
                                await UpdateManager.Current.SendXamlAsync(cacheItem.Key, cacheItem.Value, true);

                            _xamlCache.Clear();
                        }

                        _outputPane.OutputString("Requesting replacedembly update...");
                        _outputPane.OutputString(Environment.NewLine);
                    }
                }
            }
            catch(Exception ex)
            {
                _outputPane.OutputString($"Something went wrong! RealXaml was unable to send the updated replacedembly.");
                _outputPane.OutputString(Environment.NewLine);
                _outputPane.OutputString(ex.ToString());
                _outputPane.OutputString(Environment.NewLine);

                System.Diagnostics.Debug.WriteLine($"Something went wrong! RealXaml was unable to send the updated replacedembly.");
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            this.IsBuilding = false;
        }

19 Source : SendAssemblyCommand.cs
with MIT License
from admaiorastudio

private async void Execute(object sender, EventArgs e)
        {
            try
            {
                // Switch to the main thread - the call to AddCommand in SendreplacedemblyCommand's constructor requires
                // the UI thread.
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(this.package.DisposalToken);

                var dte = await this.package.GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
                var projects = dte.ActiveSolutionProjects as Array;
                var project = projects.Cast<Project>().FirstOrDefault();
                if (project == null)
                    return;

                EnvDTE.Property property = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath");
                string fullPath = project.Properties.Item("FullPath").Value.ToString();
                string outputFileName = project.Properties.Item("OutputFileName").Value.ToString();
                string outputPath = property.Value.ToString();

                string replacedemblyPath = Path.Combine(fullPath, outputPath, outputFileName);

                using (MemoryStream ms = new MemoryStream())
                {
                    // Make a copy of the file into memory to avoid any file lock                   
                    using (FileStream fs = File.OpenRead(replacedemblyPath))
                        await fs.CopyToAsync(ms);

                    UpdateManager.Current.Notifyreplacedembly(outputFileName, ms.ToArray());

                    this.OutputPane?.OutputString("Requesting replacedembly update...");
                    this.OutputPane?.OutputString(Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                this.OutputPane?.OutputString($"Something went wrong! RealXaml was unable to send the updated replacedembly.");
                this.OutputPane?.OutputString(Environment.NewLine);
                this.OutputPane?.OutputString(ex.ToString());
                this.OutputPane?.OutputString(Environment.NewLine);

                System.Diagnostics.Debug.WriteLine($"Something went wrong! RealXaml was unable to send the updated replacedembly.");
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            //dte.Solution.SolutionBuild.BuildProject(
            //    project.ConfigurationManager.ActiveConfiguration.ConfigurationName, 
            //    project.UniqueName);               
        }

19 Source : ActivationByteHashExtractor.cs
with GNU General Public License v2.0
from adrifcastr

public static string GetActivationChecksum(string path)
        {
            using (var fs = System.IO.File.OpenRead(path))
            using (var br = new BinaryReader(fs))
            {
                fs.Position = 0x251 + 56 + 4;
                var checksum = br.ReadBytes(20);
                return checksum.ToHexString();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdriaandeJongh

static string GetMD5(string filepath)
        {
            using (var md5 = MD5.Create())
            {
                using (var stream = File.OpenRead(filepath))
                {
                    return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", string.Empty).ToLowerInvariant();
                }
            }
        }

19 Source : SpeechToText.cs
with MIT License
from adrianstevens

public async Task<SpeechToTextResult> RecognizeSpeechAsync(string audioFile)
        {
            SpeechToTextResult result;

            using (FileStream stream = File.OpenRead(audioFile))
            {
                var requestUri = GetRequestUri(Constants.SpeechRecognitionEndpoint);
                var accessToken = await authenticationService.GetAccessToken();

                var response = await SendRequestAsync(stream, requestUri, accessToken, Constants.AudioContentType);

                result = JsonConvert.DeserializeObject<SpeechToTextResult>(response);
            }
            return result;
        }

19 Source : Helpers.cs
with GNU General Public License v3.0
from Aetsu

public static void CalculateMD5Files(string folder)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("     Calculating md5...");
            Console.ResetColor();
            string[] fileList = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories);
            List<string> md5List = new List<string>();
            foreach (string filename in fileList)
            {
                using (var md5 = MD5.Create())
                {
                    using (var stream = File.OpenRead(filename))
                    {
                        var hash = md5.ComputeHash(stream);
                        md5List.Add(filename + " - " + BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant());
                    }
                }
            }
            File.WriteAllLines(Path.Combine(new string[] { folder, "md5.txt" }), md5List);
        }

19 Source : WelcomeFragmentController.cs
with Apache License 2.0
from Aguafrommars

[HttpGet]
        public FileResult Get()
        {
            var path = $"{_environment.WebRootPath}/{_environment.EnvironmentName}-welcome-fragment.{CultureInfo.CurrentCulture.Name}.html";
            if (IO.File.Exists(path))
            {
                return File(IO.File.OpenRead(path), "text/htnl");
            }
            path = $"{_environment.WebRootPath}/{_environment.EnvironmentName}-welcome-fragment.html";
            if (IO.File.Exists(path))
            {
                return File(IO.File.OpenRead(path), "text/htnl");
            }
            path = $"{_environment.WebRootPath}/welcome-fragment.{CultureInfo.CurrentCulture.Name}.html";
            if (IO.File.Exists(path))
            {
                return File(IO.File.OpenRead(path), "text/htnl");
            }
            path = $"{_environment.WebRootPath}/welcome-fragment.html";
            if (IO.File.Exists(path))
            {
                return File(IO.File.OpenRead(path), "text/htnl");
            }
            return null;
        }

19 Source : TestUtils.cs
with Apache License 2.0
from Aguafrommars

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                var method = typeof(HttpMessageHandler).GetMethod("SendAsync", BindingFlags.NonPublic | BindingFlags.Instance);

                if (request.Content is MultipartFormDataContent dataContent)
                {
                    var content = new MultipartFormDataContent();
                    var fileContent = dataContent.First() as StreamContent;
                    var contentDisposition = fileContent.Headers.GetValues("Content-Disposition");
                    var fileName = contentDisposition.First().Split("; ").First(s => s.StartsWith("filename")).Split("=")[1];
                    var file = File.OpenRead(fileName);
                    content.Add(new StreamContent(file), "files", file.Name);
                    request.Content = content;

                }
                return method.Invoke(_handler, new object[] { request, cancellationToken }) as Task<HttpResponseMessage>;
            }

19 Source : BundleContainer.cs
with GNU Affero General Public License v3.0
from aianlinb

public virtual MemoryStream Read(string path = null) {
            offset = 0;
            var br = new BinaryReader(File.OpenRead(path ?? this.path));
            var ms = Read(br);
            br.Close();
            return ms;
        }

19 Source : PackageImporter.cs
with MIT License
from ai-traders

public async Task ImportAsync(string pkgDirectory, TextWriter output)
        {
            var files = GetDirectoryFiles(pkgDirectory, "*.nupkg", SearchOption.AllDirectories, output);
            foreach (string file in files)
            {
                output.Write("Importing package {0} ", file);
                using (var uploadStream = File.OpenRead(file))
                {
                    var result = await _indexingService.IndexAsync(uploadStream, CancellationToken.None);
                    output.WriteLine(result);
                }
            }
        }

19 Source : SerializeEngine.cs
with GNU General Public License v3.0
from aiportal

public static object Deserialize(string path)
		{
			using (FileStream fs = File.OpenRead(path))
			{
				BinaryFormatter bf = new BinaryFormatter();
				bf.Binder = new LocalreplacedemblyBinder();
				return bf.Deserialize(fs);
			}
		}

19 Source : Serialization.cs
with GNU General Public License v3.0
from aiportal

public static object FromBinaryFile(string path, bool verifyreplacedembly = false)
		{
			using (FileStream fs = File.OpenRead(path))
			{
				BinaryFormatter bf = new BinaryFormatter();
				if (!verifyreplacedembly)
					bf.Binder = new LocalreplacedemblyBinder();
				return bf.Deserialize(fs);
			}
		}

19 Source : CsvAsyncStreamInputTests.cs
with MIT License
from airbreather

[Theory]
        [MemberData(nameof(TestCsvFilesWithChunkLengths))]
        public async Task WithoutIgnoringUTF8BOM(string filePath, int chunkLength)
        {
            // arrange
            filePath = Path.Combine(TestCsvFilesFolderPath, filePath);
            using var stream = File.OpenRead(filePath);
            // act, replacedert
            await RunTestAsync(CreateSut, filePath, false).ConfigureAwait(true);

            CsvAsyncInputBase CreateSut()
            {
                stream.Position = 0;
                return CsvAsyncInput.ForStream(stream)
                                    .WithMinReadBufferByteCount(chunkLength)
                                    .WithIgnoreUTF8ByteOrderMark(false);
            }
        }

19 Source : CsvAsyncStreamInputTests.cs
with MIT License
from airbreather

[Theory]
        [MemberData(nameof(TestCsvFilesWithChunkLengths))]
        public async Task IgnoreUTF8BOM(string filePath, int chunkLength)
        {
            // arrange
            filePath = Path.Combine(TestCsvFilesFolderPath, filePath);
            using var stream = File.OpenRead(filePath);
            // act, replacedert
            await RunTestAsync(CreateSut, filePath, true).ConfigureAwait(true);

            CsvAsyncInputBase CreateSut()
            {
                stream.Position = 0;
                return CsvAsyncInput.ForStream(stream)
                                    .WithMinReadBufferByteCount(chunkLength)
                                    .WithIgnoreUTF8ByteOrderMark(true);
            }
        }

19 Source : CsvAsyncStreamInputTests.cs
with MIT License
from airbreather

[Theory]
        [MemberData(nameof(TestCsvFilesWithChunkLengths))]
        public async Task NoPool(string filePath, int chunkLength)
        {
            // arrange
            filePath = Path.Combine(TestCsvFilesFolderPath, filePath);
            using var stream = File.OpenRead(filePath);
            // act, replacedert
            await RunTestAsync(CreateSut, filePath, true).ConfigureAwait(true);

            CsvAsyncInputBase CreateSut()
            {
                stream.Position = 0;
                return CsvAsyncInput.ForStream(stream)
                                    .WithMinReadBufferByteCount(chunkLength)
                                    .WithReadBufferPool(null)
                                    .WithIgnoreUTF8ByteOrderMark(true);
            }
        }

19 Source : CsvSyncStreamInputTests.cs
with MIT License
from airbreather

[Theory]
        [MemberData(nameof(TestCsvFilesWithChunkLengths))]
        public void WithoutIgnoringUTF8BOM(string filePath, int chunkLength)
        {
            // arrange
            filePath = Path.Combine(TestCsvFilesFolderPath, filePath);
            using var stream = File.OpenRead(filePath);
            var sut = CsvSyncInput.ForStream(stream)
                                  .WithMinReadBufferByteCount(chunkLength)
                                  .WithIgnoreUTF8ByteOrderMark(false);

            // act, replacedert
            RunTest(sut, filePath, false);
        }

19 Source : CsvSyncStreamInputTests.cs
with MIT License
from airbreather

[Theory]
        [MemberData(nameof(TestCsvFilesWithChunkLengths))]
        public void IgnoreUTF8BOM(string filePath, int chunkLength)
        {
            // arrange
            filePath = Path.Combine(TestCsvFilesFolderPath, filePath);
            using var stream = File.OpenRead(filePath);
            var sut = CsvSyncInput.ForStream(stream)
                                  .WithMinReadBufferByteCount(chunkLength)
                                  .WithIgnoreUTF8ByteOrderMark(true);

            // act, replacedert
            RunTest(sut, filePath, true);
        }

See More Examples