System.IO.File.OpenWrite(string)

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

923 Examples 7

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

public void Handle(CelesteNetConnection con, DataNetEmoji netemoji) {
            Logger.Log(LogLevel.VVV, "netemoji", $"Received {netemoji.ID}");

            string dir = Path.Combine(Path.GetTempPath(), "CelesteNetClientEmojiCache");
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            string path = Path.Combine(dir, $"{netemoji.ID}-{netemoji.GetHashCode():X8}.png");
            using (FileStream fs = File.OpenWrite(path))
            using (MemoryStream ms = new(netemoji.Data))
                ms.CopyTo(fs);

            RunOnMainThread(() => {
                Logger.Log(LogLevel.VVV, "netemoji", $"Registering {netemoji.ID}");

                bool registered = false;

                try {
                    VirtualTexture vt = VirtualContent.CreateTexture(path);
                    MTexture mt = new(vt);
                    if (vt.Texture_Safe == null) // Needed to trigger lazy loading.
                        throw new Exception($"Couldn't load emoji {netemoji.ID}");

                    Registered.Add(netemoji.ID);
                    RegisteredFiles.Add(path);
                    Emoji.Register(netemoji.ID, mt);
                    Emoji.Fill(CelesteNetClientFont.Font);
                    registered = true;

                } finally {
                    if (!registered)
                        File.Delete(path);
                }
            });
        }

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

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

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

            string? dir = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            using (Stream stream = File.OpenWrite(path + ".tmp"))
            using (StreamWriter writer = new(stream))
                Save(writer);

            if (File.Exists(path))
                File.Delete(path);
            File.Move(path + ".tmp", path);
        }

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

public void SaveRaw<T>(string path, T data) where T : notnull {
            lock (GlobalLock) {
                string? dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                using (Stream stream = File.OpenWrite(path + ".tmp"))
                using (StreamWriter writer = new(stream))
                    YamlHelper.Serializer.Serialize(writer, data, typeof(T));

                if (File.Exists(path))
                    File.Delete(path);
                File.Move(path + ".tmp", path);
            }
        }

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

public override Stream WriteFile(string uid, string name) {
            string path = GetUserFilePath(uid, name);
            string? dir = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            if (File.Exists(path))
                File.Delete(path);
            return File.OpenWrite(path);
        }

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

private void InsertFileRaw(string path, Stream stream) {
            lock (GlobalLock) {
                string? dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                if (File.Exists(path))
                    File.Delete(path);
                Stream target = File.OpenWrite(path);
                stream.CopyTo(target);
            }
        }

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 : RedisClientBuilder.cs
with MIT License
from 2881099

public async Task OutputIntefaceAsync(string filename)
        {
            var engine = new RazorLightEngineBuilder()
                .DisableEncoding()
                .UseFileSystemProject(Directory.GetCurrentDirectory())
                .UseMemoryCachingProvider()
                .Build();

            var model = new TemplateClreplaced(methods.Select(_method=> _method.ToInterface()).ToList());

            #region Build Interface
            var result = await engine.CompileRenderAsync("Template/Inteface.cshtml", model);

            using(var writeStream = File.OpenWrite(filename))
            {
                using (var streamWrite = new StreamWriter(writeStream, Encoding.UTF8))
                    await streamWrite.WriteLineAsync(result);
            }
            #endregion
        }

19 Source : RedisClientBuilder.cs
with MIT License
from 2881099

public async Task OutputProxyAsync(string filename)
        {
            var engine = new RazorLightEngineBuilder()
                .DisableEncoding()
                .UseFileSystemProject(Directory.GetCurrentDirectory())
                .UseMemoryCachingProvider()
                .Build();

            var model = new TemplateClreplaced(methods.Select(_method => _method.ToProxy()).ToList());

            #region Build Interface
            var result = await engine.CompileRenderAsync("Template/Proxy.cshtml", model);

            using (var writeStream = File.OpenWrite(filename))
            {
                using (var streamWrite = new StreamWriter(writeStream, Encoding.UTF8))
                    await streamWrite.WriteLineAsync(result);
            }
            #endregion
        }

19 Source : RedisClientBuilder.cs
with MIT License
from 2881099

public async Task OutputRedisHelperAsync(string filename)
        {
            var engine = new RazorLightEngineBuilder()
                .DisableEncoding()
                .UseFileSystemProject(Directory.GetCurrentDirectory())
                .UseMemoryCachingProvider()
                .Build();

            var model = new TemplateClreplaced(methods.Select(_method => _method.ToMethod()).ToList());

            #region Build Interface
            var result = await engine.CompileRenderAsync("Template/Helper.cshtml", model);

            using (var writeStream = File.OpenWrite(filename))
            {
                using (var streamWrite = new StreamWriter(writeStream, Encoding.UTF8))
                    await streamWrite.WriteLineAsync(result);
            }
            #endregion
        }

19 Source : Program.cs
with MIT License
from 71

public static int Main(string[] args)
        {
            string ns = null;
            string dir = Directory.GetCurrentDirectory();
            string output = Path.Combine(Directory.GetCurrentDirectory(), OUTPUT_FILENAME);
            bool makePublic = false;

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                    case "--public":
                    case "-p":
                        makePublic = true;
                        break;
                    case "--namespace":
                    case "-n":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No namespace given.");
                            return 1;
                        }

                        ns = args[++i];
                        break;
                    case "--directory":
                    case "-d":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No directory given.");
                            return 1;
                        }

                        dir = args[++i];
                        break;
                    case "--output":
                    case "-o":
                        if (args.Length == i + 1)
                        {
                            Console.Error.WriteLine("No directory given.");
                            return 1;
                        }

                        output = args[++i];
                        break;
                    default:
                        Console.Error.WriteLine($"Unknown argument: '{args[i]}'.");
                        return 1;
                }
            }

            string methodRedirectionPath = Path.Combine(dir, "Redirection.Method.cs");
            string helpersPath = Path.Combine(dir, "Helpers.cs");

            if (!File.Exists(methodRedirectionPath) || !File.Exists(helpersPath))
            {
                Console.Error.WriteLine("Invalid directory given.");
                return 1;
            }

            try
            {
                // Read files
                string methodRedirectionContent = File.ReadAllText(methodRedirectionPath);
                string helpersContent = File.ReadAllText(helpersPath);

                // Parse content to trees, and get their root / clreplacedes / usings
                SyntaxTree methodRedirectionTree = SyntaxFactory.ParseSyntaxTree(methodRedirectionContent, path: methodRedirectionPath);
                SyntaxTree helpersTree = SyntaxFactory.ParseSyntaxTree(helpersContent, path: helpersPath);

                CompilationUnitSyntax methodRedirection = methodRedirectionTree.GetCompilationUnitRoot();
                CompilationUnitSyntax helpers = helpersTree.GetCompilationUnitRoot();

                UsingDirectiveSyntax[] usings = methodRedirection.Usings.Select(x => x.Name.ToString())
                    .Concat(helpers.Usings.Select(x => x.Name.ToString()))
                    .Distinct()
                    .OrderBy(x => x)
                    .Select(x => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(x)))
                    .ToArray();

                ClreplacedDeclarationSyntax methodRedirectionClreplaced = methodRedirection.DescendantNodes()
                                                                                 .OfType<ClreplacedDeclarationSyntax>()
                                                                                 .First();
                ClreplacedDeclarationSyntax helpersClreplaced = helpers.DescendantNodes()
                                                             .OfType<ClreplacedDeclarationSyntax>()
                                                             .First();

                // Set visibility of main clreplaced
                if (!makePublic)
                {
                    var modifiers = methodRedirectionClreplaced.Modifiers;
                    var publicModifier = modifiers.First(x => x.Kind() == SyntaxKind.PublicKeyword);

                    methodRedirectionClreplaced = methodRedirectionClreplaced.WithModifiers(
                        modifiers.Replace(publicModifier, SyntaxFactory.Token(SyntaxKind.InternalKeyword))
                    );
                }

                // Set visibility of helpers clreplaced
                helpersClreplaced = helpersClreplaced.WithModifiers(
                    helpersClreplaced.Modifiers.Replace(
                        helpersClreplaced.Modifiers.First(x => x.Kind() == SyntaxKind.InternalKeyword),
                        SyntaxFactory.Token(SyntaxKind.PrivateKeyword)
                    )
                );

                // Change helpers clreplaced extension methods to normal methods
                var extMethods = helpersClreplaced.DescendantNodes()
                                             .OfType<MethodDeclarationSyntax>()
                                             .Where(x => x.ParameterList.DescendantTokens().Any(tok => tok.Kind() == SyntaxKind.ThisKeyword));
                var extMethodsNames = extMethods.Select(x => x.Identifier.Text);

                helpersClreplaced = helpersClreplaced.ReplaceNodes(
                    helpersClreplaced.DescendantNodes().OfType<ParameterSyntax>().Where(x => x.Modifiers.Any(SyntaxKind.ThisKeyword)),
                    (x,_) => x.WithModifiers(x.Modifiers.Remove(x.Modifiers.First(y => y.Kind() == SyntaxKind.ThisKeyword)))
                );

                // Disable overrides
                var members = methodRedirectionClreplaced.Members;

                for (int i = 0; i < members.Count; i++)
                {
                    var member = members[i];

                    if (!(member is MethodDeclarationSyntax method))
                    {
                        if (member is ConstructorDeclarationSyntax ctor)
                            members = members.Replace(ctor, ctor.WithIdentifier(SyntaxFactory.Identifier("Redirection")));

                        continue;
                    }

                    var overrideModifier = method.Modifiers.FirstOrDefault(x => x.Kind() == SyntaxKind.OverrideKeyword);

                    if (overrideModifier == default(SyntaxToken))
                        continue;

                    method = method.WithModifiers(
                        method.Modifiers.Remove(overrideModifier)
                    );

                    members = members.Replace(member, method);
                }

                // Add missing field
                var field = SyntaxFactory.FieldDeclaration(
                    SyntaxFactory.VariableDeclaration(
                        SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.BoolKeyword)),
                        SyntaxFactory.SeparatedList(new[] {
                            SyntaxFactory.VariableDeclarator("isRedirecting")
                        })
                    )
                );

                const string DOCS = @"
    /// <summary>
    ///   Provides the ability to redirect calls from one method to another.
    /// </summary>
";

                var disposableType = SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(nameof(IDisposable)));

                methodRedirectionClreplaced = methodRedirectionClreplaced.WithMembers(members)
                    // Add docs
                    .WithLeadingTrivia(SyntaxFactory.Comment(DOCS))
                    // Rename to 'Redirection'
                    .WithIdentifier(SyntaxFactory.Identifier("Redirection"))
                    // Disable inheritance, but implement IDisposable
                    .WithBaseList(SyntaxFactory.BaseList().AddTypes(disposableType))
                    // Embed helpers, missing field
                    .AddMembers(field, helpersClreplaced);

                // Generate namespace (or member, if no namespace is specified)
                MemberDeclarationSyntax @namespace = ns == null
                    ? (MemberDeclarationSyntax)methodRedirectionClreplaced
                    : SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(ns)).AddMembers(methodRedirectionClreplaced);

                var extCalls = @namespace.DescendantNodes()
                                         .OfType<InvocationExpressionSyntax>()
                                         .Where(x => x.Expression is MemberAccessExpressionSyntax access && extMethodsNames.Contains(access.Name.Identifier.Text));
                var helpersAccess = SyntaxFactory.IdentifierName("Helpers");

                @namespace = @namespace.ReplaceNodes(
                    extCalls,
                    (x, _) => SyntaxFactory.InvocationExpression(((MemberAccessExpressionSyntax)x.Expression).WithExpression(helpersAccess)).WithArgumentList(x.ArgumentList.WithArguments(x.ArgumentList.Arguments.Insert(0, SyntaxFactory.Argument(((MemberAccessExpressionSyntax)x.Expression).Expression)))));

                // Generate syntax root
                CompilationUnitSyntax root = SyntaxFactory.CompilationUnit()
                                                          .AddUsings(usings)
                                                          .AddMembers(@namespace);

                // Print root to file
                using (FileStream fs = File.OpenWrite(output))
                using (TextWriter writer = new StreamWriter(fs))
                {
                    fs.SetLength(0);

                    Formatter.Format(root, new AdhocWorkspace()).WriteTo(writer);
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error encountered:");
                Console.Error.WriteLine(e.Message);
                return 1;
            }

            return 0;
        }

19 Source : SimpleJSON.cs
with MIT License
from 734843327

public void SaveToFile(string aFileName)
		{
			System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
			using(var F = System.IO.File.OpenWrite(aFileName))
			{
				SaveToStream(F);
			}
		}

19 Source : Utility.Http.cs
with MIT License
from 7Bytes-Studio

private void DownloadFileCheck()
                {
                    var tmpFileName = m_HttpDownloadInfo.SavePath +"."+ m_HttpDownloadInfo.TempFileExtension;
                    if (File.Exists(tmpFileName))
                    {
                        m_FileStream = File.OpenWrite(tmpFileName);
                        m_Position = m_FileStream.Length;
                        m_FileStream.Seek(m_Position, SeekOrigin.Current);
                    }
                    else
                    {
                        m_FileStream = new FileStream(tmpFileName, FileMode.Create);
                        m_Position = 0L;
                    }
                }

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 : Repository.cs
with Apache License 2.0
from AantCoder

public void Save(bool onlyChangeData = false)
        {
            if (onlyChangeData && !ChangeData) return;
            Loger.Log("Server Saving");

            try
            {
                if (File.Exists(SaveFileName))
                {
                    if (File.Exists(SaveFileName + ".bak")) File.Delete(SaveFileName + ".bak");
                    File.Move(SaveFileName, SaveFileName + ".bak");
                }

                Data.MaxIdChat = ChatManager.Instance.MaxChatId;

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

                ChangeData = false;
            }
            catch
            {
                if (File.Exists(SaveFileName + ".bak"))
                    File.Copy(SaveFileName + ".bak", SaveFileName, true);
                throw;
            }

            Loger.Log("Server Saved");
        }

19 Source : PerformanceAppender.cs
with MIT License
from Abc-Arbitrage

public void PrintTimeTaken()
        {
            var totalTimeCsv = "total-time.csv";
            if (File.Exists(totalTimeCsv))
                File.Delete(totalTimeCsv);

            using (var fileStream = new StreamWriter(File.OpenWrite(totalTimeCsv)))
            {
                for (int i = 0; i < _count; i++)
                {
                    var messageReceived = _messages[i];
                    var timestampString = Encoding.Default.GetString(messageReceived.StartTimestampInChars, 0, messageReceived.MessageLength);
                    var startTime = long.Parse(timestampString);
                    fileStream.WriteLine(ToMicroseconds(messageReceived.EndTimestamp - startTime));
                }
            }
        }

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

public static Stream GetFileRewriteStream(string path)
        {
            EnsureFileEmpty(path);
            return File.OpenWrite(path);
        }

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

public static async Task SaveConfigAsync(Config config, string path = ConfigurePath)
        {
            try
            {
                using (var stream = File.OpenWrite(path))
                using (var writer = new StreamWriter(stream))
                {
                    await writer.WriteLineAsync(JsonConvert.SerializeObject(config, Formatting.Indented)).ConfigureAwait(false);
                    await RequestLogAsync(new LogMessage(LogSeverity.Verbose, "Program", "The config has been saved successfully.")).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                await RequestLogAsync(new LogMessage(LogSeverity.Error, "Program", ex.Message, ex)).ConfigureAwait(false);
                throw;
            }
        }

19 Source : SimpleAudioPlayerImplementation.cs
with MIT License
from adrianstevens

public bool Load(Stream audioStream)
        {
            DeletePlayer();

            player = GetPlayer();

            if (player != null)
            {
                var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), $"{++index}.wav");
                using (var fileStream = File.OpenWrite(fileName)) audioStream.CopyTo(fileStream);

                player.Open(new Uri(fileName));
                player.MediaEnded += OnPlaybackEnded;
            }

            return player != null && player.Source != null;
        }

19 Source : VlcUtil.cs
with GNU General Public License v3.0
from aduskin

public static void ScreenshotWithWatermark(string filePath, string watermark, Brush foreground, FontWeight fontWeight, int rows = 3, int columns = 3
          , double fontSize = 36, double opacity = 0.3, double angle = -20)
      {
         BitmapImage bgImage;

         //从流中读取图片,防止出现资源被占用的问题
         using (BinaryReader reader = new BinaryReader(File.Open(filePath, FileMode.Open)))
         {
            FileInfo fi = new FileInfo(filePath);
            byte[] bytes = reader.ReadBytes((int)fi.Length);

            bgImage = new BitmapImage();
            bgImage.BeginInit();
            bgImage.StreamSource = new MemoryStream(bytes);
            bgImage.EndInit();
            bgImage.CacheOption = BitmapCacheOption.OnLoad;
         }

         RenderTargetBitmap composeImage = new RenderTargetBitmap(bgImage.PixelWidth, bgImage.PixelHeight, bgImage.DpiX, bgImage.DpiY, PixelFormats.Default);

         fontSize = GetFontSizeByPixel(bgImage.PixelHeight, fontSize);

         //设置水印文字效果:字体、颜色等
#if NETCOREAPP
         FormattedText signatureTxt = new FormattedText(watermark, CultureInfo.CurrentCulture, FlowDirection.LeftToRight
             , new Typeface(SystemFonts.MessageFontFamily, FontStyles.Normal, fontWeight, FontStretches.Normal), fontSize, foreground,
             VisualTreeHelper.GetDpi(Application.Current.MainWindow).PixelsPerDip);
#else
            FormattedText signatureTxt = new FormattedText(watermark, CultureInfo.CurrentCulture, FlowDirection.LeftToRight
                , new Typeface(SystemFonts.MessageFontFamily, FontStyles.Normal, fontWeight, FontStretches.Normal), fontSize, foreground);
#endif

         DrawingVisual drawingVisual = new DrawingVisual();
         DrawingContext drawingContext = drawingVisual.RenderOpen();
         drawingContext.DrawImage(bgImage, new Rect(0, 0, bgImage.Width, bgImage.Height));

         #region 设置水印的旋转角度及透明度,需要在绘制水印文本之前设置,否则不生效
         //x,y为水印旋转的中心点
         double centerX = (bgImage.Width - signatureTxt.Width) / 2;
         double centerY = (bgImage.Height - signatureTxt.Height) / 2;

         //设置水印透明度
         drawingContext.PushOpacity(opacity);
         //设置水印旋转角度
         drawingContext.PushTransform(new RotateTransform(angle, centerX, centerY));
         #endregion

         #region 绘制全屏水印
         double intervalX = bgImage.Width / columns; //水印水平间隔
         double intervalY = bgImage.Height / rows; //水印垂直间隔

         //水印绘制方向:从上往下,再从左到右
         for (double i = 0; i < bgImage.Width; i += intervalX)
         {
            for (double j = 0; j < bgImage.Height + intervalY; j += intervalY)
            {
               //奇偶行间隔绘制水印
               if ((j / intervalY) % 2 == 0)
               {
                  drawingContext.DrawText(signatureTxt, new Point(i, j));
               }
               else
               {
                  drawingContext.DrawText(signatureTxt, new Point(i + intervalX / 2, j));
               }
            }
         }
         #endregion

         drawingContext.Close();

         composeImage.Render(drawingVisual);

         PngBitmapEncoder bitmapEncoder = new PngBitmapEncoder();
         bitmapEncoder.Frames.Add(BitmapFrame.Create(composeImage));

         //删除VLC生成的原始截图
         File.Delete(filePath);

         //将合成水印的截图保存到本地
         using (Stream stream = File.OpenWrite(filePath))
         {
            bitmapEncoder.Save(stream);
         }
         bgImage = null;
      }

19 Source : FileExplorer.cs
with MIT License
from aerosoul94

private void WriteFile(string path, DirectoryEntry dirent, List<uint> chainMap)
            {
                using (FileStream outFile = File.OpenWrite(path))
                {
                    uint bytesLeft = dirent.FileSize;

                    foreach (uint cluster in chainMap)
                    {
                        byte[] clusterData = this.volume.ReadCluster(cluster);

                        var writeSize = Math.Min(bytesLeft, this.volume.BytesPerCluster);
                        outFile.Write(clusterData, 0, (int)writeSize);

                        bytesLeft -= writeSize;
                    }
                }
            }

19 Source : RecoveryResults.cs
with MIT License
from aerosoul94

private void WriteFile(string path, DatabaseFile databaseFile)
            {
                using (FileStream outFile = File.OpenWrite(path))
                {
                    uint bytesLeft = databaseFile.FileSize;

                    foreach (uint cluster in databaseFile.ClusterChain)
                    {
                        byte[] clusterData = this.volume.ReadCluster(cluster);

                        var writeSize = Math.Min(bytesLeft, this.volume.BytesPerCluster);
                        outFile.Write(clusterData, 0, (int)writeSize);

                        bytesLeft -= writeSize;
                    }
                }
            }

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

static int Main(string[] args)
        {
            string gtaPath = KeyUtil.FindGTADirectory();
            while (gtaPath == null)
            {
                Console.Error.WriteLine("ERROR");
                Console.Error.WriteLine("Could not find GTAIV directory. Please install GTAIV or copy EFLC.exe\n" +
                                    "to the same path as Scruff.");
                return 1;
            }

            byte[] key = KeyUtil.FindKey(gtaPath);
            if (key == null)
            {
                Console.Error.WriteLine("ERROR");
                Console.Error.WriteLine("Your EFLC.exe seems to be modified or is a newer version than this tool\n" +
                                        "supports. If it is a newer version, please check for an update of Scruff.\n" +
                                        "Scruff can not run without a supported EFLC.exe file.");
                return 1;
            }

            KeyStore.SetKeyLoader(() => key);


            CodeFormatOptions[] formats = 
                {
                    new CodeFormatOptions("d", CodeFormat.ScruffDecompile, "Default Scruff disreplacedembly format"),
                    new CodeFormatOptions("h", CodeFormat.ScruffHeader, "Default Scruff header/local varibles/etc format"),
                    new CodeFormatOptions("hl", CodeFormat.FullDecompile, "High level C-like format"),
                    new CodeFormatOptions("hla", CodeFormat.FullDecompileAnnotate, "High level C-like format (annotated)"),
                    new CodeFormatOptions("ll", CodeFormat.Disreplacedemble, "Low level raw replacedembly format"),
                    new CodeFormatOptions("cp", CodeFormat.CodePath, "Code path for the control-flow-replacedyzer (for debugging)"),
                };

            CodeFormat customFormat = CodeFormat.ScruffDecompile;
            bool defaultMode = true;
            string filename = null;
            string outputFilename = null;

            if (args.Length > 0)
            {
                var argsQueue = new Queue<string>(args);

                while (argsQueue.Count > 0)
                {
                    var arg = argsQueue.Dequeue();
                    if (arg.StartsWith("-"))
                    {
                        if (arg == "-o")
                        {
                            defaultMode = false;
                            outputFilename = argsQueue.Dequeue();
                        }
                        else
                        {
                            foreach (var format in formats)
                            {
                                if (arg == "-" + format.Param)
                                {
                                    defaultMode = false;
                                    customFormat = format.Format;
                                    break;
                                }
                            }                            
                        }
                    }
                    else
                    {
                        if (argsQueue.Count > 0)
                        {
                            break;
                        }
                        filename = arg;
                    }
                }
            }

            if (filename == null)
            {
                var formatParams = new StringBuilder();
                foreach (var format in formats)
                {
                    if (formatParams.Length > 0)
                    {
                        formatParams.Append("|");
                    }
                    formatParams.Append("-");
                    formatParams.Append(format.Param);
                }

                Console.Error.WriteLine("Scruff - A RAGE Script File Decompiler/Disreplacedembler");
                Console.Error.WriteLine("v" + Version + " -- (c) 2008-2009, Aru <oneforaru at gmail dot com>");
                Console.Error.WriteLine();
                Console.Error.WriteLine(string.Format("Usage: scruff [{0}] [-o filename.sca] filename.sco", formatParams));
                Console.Error.WriteLine();
                Console.Error.WriteLine("By default, will generate filename.sca (-d) and filename.sch (-h)");
                Console.Error.WriteLine("If output file is specified, only filename.sca will be generated.");
                Console.Error.WriteLine("If format specified without output filename, will dump to console (stdout).");
                Console.Error.WriteLine();
                Console.Error.WriteLine("For custom options, use:");
                Console.Error.WriteLine("    -{0,-5} {1}", "o", "Saves the result to a specified file.");
                foreach (var format in formats)
                {
                    Console.Error.WriteLine("    -{0,-5} {1}", format.Param, format.Description);
                }
                Console.Error.WriteLine();
                /*
                Console.Error.WriteLine("Press any key to exit");
                Console.ReadKey();
                 */
                return 1;
            }

            var file = new ScriptFile();

            try
            {
                file.Open(filename);
            }
            catch
            {
                Console.Error.WriteLine("Invalid input file -- not a valid script.");
                /*
                Console.ReadKey();
                 */
                return 1;
            }

            if (defaultMode)
            {
                using (var fs = File.OpenWrite(Path.ChangeExtension(filename, "sca")))
                {
                    var sw = new StreamWriter(fs);
                    OutputCode(file, CodeFormat.ScruffDecompile, sw);
                    sw.Flush();
                }

                using (var fs = File.OpenWrite(Path.ChangeExtension(filename, "sch")))
                {
                    var sw = new StreamWriter(fs);
                    OutputCode(file, CodeFormat.ScruffHeader, sw);
                    sw.Flush();
                }
            }
            else
            {
                if (outputFilename != null)
                {
                    using(var fs = File.OpenWrite(outputFilename))
                    {
                        var sw = new StreamWriter(fs);
                        OutputCode(file, customFormat, sw);
                        sw.Flush();
                    }
                }
                else
                {
                    OutputCode(file, customFormat, Console.Out);                    
                }

            }

#if DEBUG
            Console.ReadLine();
#endif

            return 0;
        }

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

public virtual void Save(Stream newData, string savePath) {
            var bw = new BinaryWriter(File.OpenWrite(savePath ?? path));

            uncompressed_size = (int)(size_decompressed = newData.Length);
            entry_count = uncompressed_size / chunk_size;
            if (uncompressed_size % chunk_size != 0) entry_count++;
            head_size = entry_count * 4 + 48;

            bw.BaseStream.Seek(60 + entry_count * 4, SeekOrigin.Begin);
            newData.Seek(0, SeekOrigin.Begin);
            compressed_size = 0;
            var chunks = new int[entry_count];
            for (var i = 0; i < entry_count; i++) {
                var b = new byte[i + 1 == entry_count ? uncompressed_size - (entry_count - 1) * chunk_size : chunk_size];
                newData.Read(b, 0, b.Length);
                var by = new byte[b.Length + 548];
                var l = OodleLZ_Compress(encoder, b, b.Length, by, Compression_Level, IntPtr.Zero, 0, 0, IntPtr.Zero, 0);
                compressed_size += chunks[i] = l;
                bw.Write(by, 0, l);
            }
            size_compressed = compressed_size;

            bw.BaseStream.Seek(60, SeekOrigin.Begin);
            foreach (var c in chunks) bw.Write(c);

            bw.BaseStream.Seek(0, SeekOrigin.Begin);
            bw.Write(uncompressed_size);
            bw.Write(compressed_size);
            bw.Write(head_size);
            bw.Write((uint)encoder);
            bw.Write(unknown);
            bw.Write(size_decompressed);
            bw.Write(size_compressed);
            bw.Write(entry_count);
            bw.Write(chunk_size);
            bw.Write(unknown3);
            bw.Write(unknown4);
            bw.Write(unknown5);
            bw.Write(unknown6);

            bw.Flush();
            bw.Close();
        }

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

public static void BitmapSourceSave(BitmapSource bitmapSource, string path) {
            var pbe = new PngBitmapEncoder();
            pbe.Frames.Add(BitmapFrame.Create(bitmapSource));
            var f = File.OpenWrite(path);
            pbe.Save(f);
            f.Flush();
            f.Close();
        }

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

public static void ToBinaryFile(object obj, string path)
		{
			using (FileStream fs = File.OpenWrite(path))
			{
				BinaryFormatter bf = new BinaryFormatter();
				bf.Serialize(fs, obj);
			}
		}

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

public static void Serialize(object obj, string path)
		{
			using (FileStream fs = File.OpenWrite(path))
			{
				BinaryFormatter bf = new BinaryFormatter();
				bf.Serialize(fs, obj);
			}
		}

19 Source : ImageCompressor.cs
with MIT License
from AiursoftWeb

private async Task SaveCompressedImage(string sourceImage, string saveTarget, int width, int height)
        {
            var fileExists = File.Exists(saveTarget);
            var fileCanRead = FileCanBeRead(saveTarget);
            if (fileExists && fileCanRead)
            {
                return;
            }
            if (fileExists)
            {
                while (!FileCanBeRead(saveTarget))
                {
                    await Task.Delay(500);
                }
            }
            else
            {
                lock (ObjCompareLock)
                {
                    // Create file
                    using var stream = File.OpenWrite(saveTarget);
                    // Load and compress file
                    var image = Image.Load(sourceImage, out IImageFormat format);
                    image.Mutate(x => x.AutoOrient());
                    image.Metadata.ExifProfile = null;
                    image.Mutate(x => x
                        .Resize(width, height));
                    image.Save(stream, format);
                    stream.Close();
                }
            }
        }

19 Source : ImageCompressor.cs
with MIT License
from AiursoftWeb

private async Task ClearImage(string sourceImage, string saveTarget)
        {
            var fileExists = File.Exists(saveTarget);
            var fileCanRead = FileCanBeRead(saveTarget);
            if (fileExists && fileCanRead)
            {
                return;
            }
            if (fileExists)
            {
                while (!FileCanBeRead(saveTarget))
                {
                    await Task.Delay(500);
                }
            }
            else
            {
                lock (ObjClearLock)
                {
                    using var stream = File.OpenWrite(saveTarget);
                    var image = Image.Load(sourceImage, out IImageFormat format);
                    image.Mutate(x => x.AutoOrient());
                    image.Metadata.ExifProfile = null;
                    image.Save(stream, format);
                    stream.Close();
                }
            }
        }

19 Source : Common.cs
with MIT License
from AlbertMN

static void InternalPreloadUnmanagedLibraries(string tempBasePath, IEnumerable<string> libs, Dictionary<string, string> checksums)
    {
        string name;

        foreach (var lib in libs)
        {
            name = ResourceNameToPath(lib);

            var replacedemblyTempFilePath = Path.Combine(tempBasePath, name);

            if (File.Exists(replacedemblyTempFilePath))
            {
                var checksum = CalculateChecksum(replacedemblyTempFilePath);
                if (checksum != checksums[lib])
                    File.Delete(replacedemblyTempFilePath);
            }

            if (!File.Exists(replacedemblyTempFilePath))
            {
                using (var copyStream = LoadStream(lib))
                using (var replacedemblyTempFile = File.OpenWrite(replacedemblyTempFilePath))
                {
                    CopyTo(copyStream, replacedemblyTempFile);
                }
                if (!MoveFileEx(replacedemblyTempFilePath, null, DelayUntilReboot))
                {
                    //TODO: for now we ignore the return value.
                }
            }
        }

        SetDllDirectory(tempBasePath);

        foreach (var lib in libs)
        {
            name = ResourceNameToPath(lib);

            if (name.EndsWith(".dll"))
            {
                var replacedemblyTempFilePath = Path.Combine(tempBasePath, name);

                LoadLibrary(replacedemblyTempFilePath);
            }
        }
    }

19 Source : PerformanceTestsRunner.cs
with MIT License
from alelievr

[MenuItem("Window/Procedural Worlds/Run performance tests", priority = 10)]
		public static void Run()
		{
			string[] performanceGraphGUIDs = replacedetDatabase.Findreplacedets("performance* t:WorldGraph");

			//empty log file:
			File.WriteAllText(logFilePath, string.Empty);

			logFile = new StreamWriter(File.OpenWrite(logFilePath));

			var resultsList = new List< PerformanceResultMulti >();

			ProfilerDriver.ClearAllFrames();
			ProfilerDriver.deepProfiling = true;
			Profiler.logFile = tmpProfilerLogFile;
			Profiler.enabled = true;

			foreach (var performanceGraphGUID in performanceGraphGUIDs)
			{
				string path = replacedetDatabase.GUIDToreplacedetPath(performanceGraphGUID);
				WorldGraph graph = replacedetDatabase.LoadreplacedetAtPath(path, typeof(WorldGraph)) as WorldGraph;

				var results = new PerformanceResultMulti(tesreplacederationCount);

				for (int i = 0; i < tesreplacederationCount; i++)
					results.results[i] = RunTestForGraph(graph);
				
				resultsList.Add(results);
			}
			
			Profiler.enabled = false;
			ProfilerDriver.deepProfiling = false;

			//this is totally broken in 2017.3 ...
			#if !UNITY_2017_3
				
				ProfilerDriver.LoadProfile(tmpProfilerLogFile, false);
	
				ProfilerDriver.SaveProfile(profilerDataFile);

			#endif

			string text = SerializeResults(resultsList);

			string reportPerfs = Environment.GetEnvironmentVariable("PW_REPORT_PERFORMANCES");

			if (reportPerfs == "ON")
			{
				ReportPerformaces(resultsList);
			}

			logFile.Write(text);
			logFile.Flush();
		}

19 Source : SaveLoad.cs
with GNU General Public License v3.0
from AlexandreDoucet

public static void Save(T serializableClreplaced, string fileName, string dataPath)
        {

            if (dataPath == null)
            {dataPath = Application.dataPath;}

            string destination = dataPath + Path.DirectorySeparatorChar + fileName;
            
            FileStream file;
            
            if (File.Exists(destination)) file = File.OpenWrite(destination)/*+".dat"*/;
            else file = File.Create(destination);
            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(file, serializableClreplaced);
            file.Close();
            Debug.Log("Saved to : " + destination);
        }

19 Source : FileAttachmentControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task SaveAction()
        {
            var extension = FileAttachment.GroupMeDoreplacedentMimeTypeMapper.MimeTypeToExtension(this.FileData.MimeType);

            var fileDialogService = Ioc.Default.GetService<IFileDialogService>();
            var filters = new List<FileFilter>
            {
                new FileFilter() { Name = "Doreplacedent", Extensions = { extension } },
            };

            var filename = fileDialogService.ShowSaveFileDialog("Save Doreplacedent", filters, this.FileData.FileName);
            if (!string.IsNullOrEmpty(filename))
            {
                this.IsLoading = true;
                var data = await this.FileAttachment.DownloadFileAsync(this.Message);

                using (var fs = File.OpenWrite(filename))
                {
                    fs.Write(data, 0, data.Length);
                }

                this.IsLoading = false;
            }
        }

19 Source : ViewImageControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task SaveImageAction()
        {
            var saveFileDialog = new SaveFileDialog();

            var imageUrlWithoutLongId = this.ImageAttachment.Url.Substring(0, this.ImageAttachment.Url.LastIndexOf('.'));
            var extension = System.IO.Path.GetExtension(imageUrlWithoutLongId).Substring(1);

            saveFileDialog.DefaultExtension = extension;
            saveFileDialog.Filters.Add(new FileDialogFilter() { Name = "PNG Image", Extensions = { "png" } });

            var fileName = await saveFileDialog.ShowAsync(Program.GroupMeMainWindow);

            if (!string.IsNullOrEmpty(fileName))
            {
                using var fs = File.OpenWrite(fileName);
                this.Image.Save(fs);
            }
        }

19 Source : ViewImageControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void SaveImageAction()
        {
            var imageUrlWithoutLongId = this.ImageUrl.Substring(0, this.ImageUrl.LastIndexOf('.'));
            var extension = Path.GetExtension(imageUrlWithoutLongId);

            var fileDialogService = Ioc.Default.GetService<IFileDialogService>();
            var filters = new List<FileFilter>
            {
                new FileFilter() { Name = "Image", Extensions = { extension } },
            };

            var filename = fileDialogService.ShowSaveFileDialog("Save Attachment", filters);
            if (!string.IsNullOrEmpty(filename))
            {
                using (var fs = File.OpenWrite(filename))
                {
                    this.ImageStream.Seek(0, SeekOrigin.Begin);
                    this.ImageStream.CopyTo(fs);
                }
            }
        }

19 Source : Win10ToastNotificationsProvider.cs
with GNU General Public License v3.0
from alexdillon

private async Task<string> DownloadImageToDiskCached(string image, bool isAvatar = false, bool isRounded = false)
        {
            // Toasts can live for up to 3 days, so we cache images for up to 3 days.
            // Note that this is a very simple cache that doesn't account for space usage, so
            // this could easily consume a lot of space within the span of 3 days.
            if (image == null)
            {
                image = string.Empty;
            }

            try
            {
                var directory = Directory.CreateDirectory(this.ToastImagePath);

                if (!this.HasPerformedCleanup)
                {
                    // First time we run, we'll perform cleanup of old images
                    this.HasPerformedCleanup = true;

                    foreach (var d in directory.EnumerateDirectories())
                    {
                        if (d.LastAccessTime.Date < DateTime.UtcNow.Date.AddDays(-3))
                        {
                            d.Delete(true);
                        }
                    }
                }

                string hashName = HashUtils.SHA1Hash(image) + ".png";
                string imagePath = Path.Combine(directory.FullName, hashName);

                if (File.Exists(imagePath))
                {
                    return imagePath;
                }

                byte[] imageData;

                if (isAvatar)
                {
                    imageData = await this.GroupMeClient.ImageDownloader.DownloadAvatarImageAsync(image, !isRounded);
                }
                else
                {
                    imageData = await this.GroupMeClient.ImageDownloader.DownloadPostImageAsync(image);
                }

                using (var fileStream = File.OpenWrite(imagePath))
                {
                    await fileStream.WriteAsync(imageData, 0, imageData.Length);
                }

                return imagePath;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

19 Source : Win10ToastNotificationsProvider.cs
with GNU General Public License v3.0
from alexdillon

private async Task<string> DownloadImageToDiskCached(string image, bool isAvatar = false, bool isRounded = false)
        {
            // Toasts can live for up to 3 days, so we cache images for up to 3 days.
            // Note that this is a very simple cache that doesn't account for space usage, so
            // this could easily consume a lot of space within the span of 3 days.
            if (image == null)
            {
                image = string.Empty;
            }

            try
            {
                var directory = Directory.CreateDirectory(this.ToastImagePath);

                if (!this.HasPerformedCleanup)
                {
                    // First time we run, we'll perform cleanup of old images
                    this.HasPerformedCleanup = true;

                    foreach (var d in directory.EnumerateDirectories())
                    {
                        if (d.LastAccessTime.Date < DateTime.UtcNow.Date.AddDays(-3))
                        {
                            d.Delete(true);
                        }
                    }
                }

                string hashName = this.Hash(image) + ".png";
                string imagePath = Path.Combine(directory.FullName, hashName);

                if (File.Exists(imagePath))
                {
                    return imagePath;
                }

                byte[] imageData;

                if (isAvatar)
                {
                    imageData = await this.GroupMeClient.ImageDownloader.DownloadAvatarImageAsync(image, !isRounded);
                }
                else
                {
                    imageData = await this.GroupMeClient.ImageDownloader.DownloadPostImageAsync(image);
                }

                using (var fileStream = File.OpenWrite(imagePath))
                {
                    await fileStream.WriteAsync(imageData, 0, imageData.Length);
                }

                return imagePath;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

19 Source : FileAttachmentControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task SaveAction()
        {
            var extension = FileAttachment.GroupMeDoreplacedentMimeTypeMapper.MimeTypeToExtension(this.FileData.MimeType);

            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.InitialFileName = this.FileData.FileName;
            saveFileDialog.Filters.Add(new FileDialogFilter() { Name = "Doreplacedent", Extensions = { extension } });

            var fileName = await saveFileDialog.ShowAsync(Program.GroupMeMainWindow);

            if (!string.IsNullOrEmpty(fileName))
            {
                this.IsLoading = true;
                var data = await this.FileAttachment.DownloadFileAsync(this.MessageContainer.Messages.First());

                using (var fs = File.OpenWrite(fileName))
                {
                    fs.Write(data, 0, data.Length);
                }

                this.IsLoading = false;
            }
        }

19 Source : AppInit.cs
with MIT License
from alexis-

public static void Initialize(IAppHost appHost)
    {
      appHost.OnPreInitialize();

      try
      {
        string appDataFolder = Const.GetAppDataFolderPath();

        Directory.CreateDirectory(appDataFolder);

        Logger.Instance.Initialize();
      }
      catch (Exception ex)
      {
        string tmpFilePath = Path.GetTempFileName();

        using (Stream s = File.OpenWrite(tmpFilePath))
        using (StreamWriter sw = new StreamWriter(s))
          sw.Write(ex.Message);

        throw new Exception(
          String.Format(LoggerInitErrorMsg, Logger.GetLogFilePath(), tmpFilePath, ex.Message),
          ex
        );
      }

      appHost.OnPostInitialize();
    }

19 Source : TableExport.cs
with MIT License
from alexis-

private void Export(IWorkbook workbook, string filepath)
    {
      ISheet sheet = workbook.CreateSheet(
        String.Format(
          "Benchmark {0}",
          DateTime.Now.ToShortDateString()
        )
      );

      int rowNum = 0;

      // Create header
      IRow headerRow = sheet.CreateRow(rowNum);
      headerRow.CreateCell(0).SetCellValue("Archive");
      headerRow.CreateCell(1).SetCellValue("Compression");
      headerRow.CreateCell(2).SetCellValue("Protocol");
      headerRow.CreateCell(3).SetCellValue("Algorithm");
      headerRow.CreateCell(4).SetCellValue("Compressed Size");
      headerRow.CreateCell(5).SetCellValue("Compression Ratio");
      headerRow.CreateCell(6).SetCellValue("Total Runtime");
      headerRow.CreateCell(7).SetCellValue("Mean Runtime");
      headerRow.CreateCell(8).SetCellValue("Median Runtime");

      foreach (var res in Results)
      {
        IRow row = sheet.CreateRow(++rowNum);

        row.CreateCell(0).SetCellValue(res.ArchiveType.ToString());
        row.CreateCell(1).SetCellValue(res.CompressionType.ToString());
        row.CreateCell(2).SetCellValue(res.EncryptionProtocol.ToString());
        row.CreateCell(3).SetCellValue(res.EncryptionAlgorithm.GetDisplayName());
        row.CreateCell(4).SetCellValue(res.CompressedSize);
        row.CreateCell(5).SetCellValue(String.Format("{0}%", res.CompressedSize == 0 ? 100 : (double)res.CompressedSize / (double)OriginalSize * 100d));
        row.CreateCell(6).SetCellValue(res.TotalRuntime);
        row.CreateCell(7).SetCellValue(res.TotalRuntime / Iterations);
        row.CreateCell(8).SetCellValue(0);
      }

      using (Stream outStream = File.OpenWrite(filepath))
        workbook.Write(outStream);
    }

19 Source : ParquetMrIntegrationTest.cs
with MIT License
from aloneguid

private void CompareWithMr(Table t)
      {
         string testFileName = Path.GetFullPath("temp.parquet");

         if (F.Exists(testFileName))
            F.Delete(testFileName);

         //produce file
         using (Stream s = F.OpenWrite(testFileName))
         {
            using (var writer = new ParquetWriter(t.Schema, s))
            {
               writer.Write(t);
            }
         }

         //read back
         Table t2 = ParquetReader.ReadTableFromFile(testFileName);

         //check we don't have a bug internally before launching MR
         replacedert.Equal(t.ToString("j"), t2.ToString("j"), ignoreLineEndingDifferences: true);

         string mrJson = ExecAndGetOutput(_javaExecName, $"-jar {_toolsJarPath} cat -j {testFileName}");
         replacedert.Equal(t.ToString("j"), mrJson);
      }

19 Source : ParquetReaderTest.cs
with MIT License
from aloneguid

[Fact]
      public void ParquetReader_OpenFromFile_Close_Stream()
      {
         // copy a file to a temp location
         string tempFile = Path.GetTempFileName();
         using (Stream fr = OpenTestFile("map_simple.parquet"))
         using (FileStream fw = System.IO.File.OpenWrite(tempFile))
         {
            fr.CopyTo(fw);
         }
               
         // open the copy
         using (var reader = ParquetReader.OpenFromFile(tempFile))
         {
            // do nothing
         }
         
         // now try to delete this temp file. If the stream is properly closed, this should succeed
         System.IO.File.Delete(tempFile);
      }

19 Source : Program.cs
with MIT License
from aloneguid

static void CompressNew(string src, string dest)
      {
         using (FileStream streamDest = F.OpenWrite(dest))
         {
            using (Stream streamSnappy = IronSnappy.Snappy.OpenWriter(streamDest))
            {
               using(FileStream streamSrc = F.OpenRead(src))
               {
                  using(var time = new TimeMeasure())
                  {
                     streamSrc.CopyTo(streamSnappy);

                     TimeSpan duration = time.Elapsed;

                     Console.WriteLine($"new: {src} => {dest}. {duration} {new FileInfo(dest).Length}");
                  }
               }
            }
         }
      }

19 Source : LocalDiskFileStorage.cs
with Apache License 2.0
from aloneguid

private Stream CreateStream(string fullPath, bool overwrite = true)
      {
         if(!SysIO.Directory.Exists(_directoryFullName))
            SysIO.Directory.CreateDirectory(_directoryFullName);
         string path = GetFilePath(fullPath);

         SysIO.Directory.CreateDirectory(Path.GetDirectoryName(path));
         Stream s = overwrite ? SysIO.File.Create(path) : SysIO.File.OpenWrite(path);
         s.Seek(0, SeekOrigin.End);
         return s;
      }

19 Source : Program.cs
with MIT License
from aloneguid

private static void ReadLargeFile(out TimeSpan readTime,
         out TimeSpan uncompressedWriteTime,
         out TimeSpan gzipWriteTime)
      {
         Schema schema;
         DataColumn[] columns;

         using (var time = new TimeMeasure())
         {
            using (var reader = ParquetReader.OpenFromFile(@"C:\dev\parquet-dotnet\src\Parquet.Test\data\customer.impala.parquet", new ParquetOptions { TreatByteArrayreplacedtring = true }))
            {
               schema = reader.Schema;
               var cl = new List<DataColumn>();

               using (ParquetRowGroupReader rgr = reader.OpenRowGroupReader(0))
               {
                  foreach (DataField field in reader.Schema.GetDataFields())
                  {
                     DataColumn dataColumn = rgr.ReadColumn(field);
                     cl.Add(dataColumn);
                  }
               }
               columns = cl.ToArray();
            }
            readTime = time.Elapsed;
         }

         using (FileStream dest = F.OpenWrite("perf.uncompressed.parquet"))
         {
            using (var time = new TimeMeasure())
            {
               using (var writer = new ParquetWriter(schema, dest))
               {
                  writer.CompressionMethod = CompressionMethod.None;
                  using (ParquetRowGroupWriter rg = writer.CreateRowGroup())
                  {
                     foreach (DataColumn dc in columns)
                     {
                        rg.WriteColumn(dc);
                     }
                  }
               }

               uncompressedWriteTime = time.Elapsed;
            }
         }


         using (FileStream dest = F.OpenWrite("perf.gzip.parquet"))
         {
            using (var time = new TimeMeasure())
            {
               using (var writer = new ParquetWriter(schema, dest))
               {
                  writer.CompressionMethod = CompressionMethod.Gzip;
                  using (ParquetRowGroupWriter rg = writer.CreateRowGroup())
                  {
                     foreach (DataColumn dc in columns)
                     {
                        rg.WriteColumn(dc);
                     }
                  }
               }

               gzipWriteTime = time.Elapsed;
            }
         }

      }

19 Source : DocRef.cs
with MIT License
from aloneguid

public void WriteIntro()
      {
         //create data columns with schema metadata and the data you need
         var idColumn = new DataColumn(
            new DataField<int>("id"),
            new int[] { 1, 2 });

         var cityColumn = new DataColumn(
            new DataField<string>("city"),
            new string[] { "London", "Derby" });

         // create file schema
         var schema = new Schema(idColumn.Field, cityColumn.Field);

         using (Stream fileStream = System.IO.File.OpenWrite("c:\\test.parquet"))
         {
            using (var parquetWriter = new ParquetWriter(schema, fileStream))
            {
               // create a new row group in the file
               using (ParquetRowGroupWriter groupWriter = parquetWriter.CreateRowGroup())
               {
                  groupWriter.WriteColumn(idColumn);
                  groupWriter.WriteColumn(cityColumn);
               }
            }
         }
      }

19 Source : WebUtil.cs
with MIT License
from AmazingDM

public static async Task DownloadFileAsync(HttpWebRequest req, string fileFullPath)
        {
            using var webResponse = (HttpWebResponse) await req.GetResponseAsync();
            using var input = webResponse.GetResponseStream();
            using var fileStream = File.OpenWrite(fileFullPath);

            await input.CopyToAsync(fileStream);
            fileStream.Flush();
        }

19 Source : Program.cs
with MIT License
from amerkoleci

private unsafe void SaveScreenshot(string path, ContainerFormat format = ContainerFormat.Jpeg)
            {
                var d3d11GraphicsDevice = ((D3D11GraphicsDevice)_graphicsDevice!);
                ID3D11Texture2D source = Headless ? d3d11GraphicsDevice!.OffscreenTexture : d3d11GraphicsDevice!.BackBufferTexture;

                path = Path.Combine(AppContext.BaseDirectory, path);

                using (ID3D11Texture2D staging = d3d11GraphicsDevice!.CaptureTexture(source))
                {
                    staging.DebugName = "STAGING";

                    var textureDesc = staging!.Description;

                    // Determine source format's WIC equivalent
                    Guid pfGuid = default;
                    bool sRGB = false;
                    switch (textureDesc.Format)
                    {
                        case Vortice.DXGI.Format.R32G32B32A32_Float:
                            pfGuid = WICPixelFormat.Format128bppRGBAFloat;
                            break;

                        //case DXGI_FORMAT_R16G16B16A16_FLOAT: pfGuid = GUID_WICPixelFormat64bppRGBAHalf; break;
                        //case DXGI_FORMAT_R16G16B16A16_UNORM: pfGuid = GUID_WICPixelFormat64bppRGBA; break;
                        //case DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102XR; break; // DXGI 1.1
                        //case DXGI_FORMAT_R10G10B10A2_UNORM: pfGuid = GUID_WICPixelFormat32bppRGBA1010102; break;
                        //case DXGI_FORMAT_B5G5R5A1_UNORM: pfGuid = GUID_WICPixelFormat16bppBGRA5551; break;
                        //case DXGI_FORMAT_B5G6R5_UNORM: pfGuid = GUID_WICPixelFormat16bppBGR565; break;
                        //case DXGI_FORMAT_R32_FLOAT: pfGuid = GUID_WICPixelFormat32bppGrayFloat; break;
                        //case DXGI_FORMAT_R16_FLOAT: pfGuid = GUID_WICPixelFormat16bppGrayHalf; break;
                        //case DXGI_FORMAT_R16_UNORM: pfGuid = GUID_WICPixelFormat16bppGray; break;
                        //case DXGI_FORMAT_R8_UNORM: pfGuid = GUID_WICPixelFormat8bppGray; break;
                        //case DXGI_FORMAT_A8_UNORM: pfGuid = GUID_WICPixelFormat8bppAlpha; break;

                        case Vortice.DXGI.Format.R8G8B8A8_UNorm:
                            pfGuid = WICPixelFormat.Format32bppRGBA;
                            break;

                        case Vortice.DXGI.Format.R8G8B8A8_UNorm_SRgb:
                            pfGuid = WICPixelFormat.Format32bppRGBA;
                            sRGB = true;
                            break;

                        case Vortice.DXGI.Format.B8G8R8A8_UNorm: // DXGI 1.1
                            pfGuid = WICPixelFormat.Format32bppBGRA;
                            break;

                        case Vortice.DXGI.Format.B8G8R8A8_UNorm_SRgb: // DXGI 1.1
                            pfGuid = WICPixelFormat.Format32bppBGRA;
                            sRGB = true;
                            break;

                        case Vortice.DXGI.Format.B8G8R8X8_UNorm: // DXGI 1.1
                            pfGuid = WICPixelFormat.Format32bppBGR;
                            break;

                        case Vortice.DXGI.Format.B8G8R8X8_UNorm_SRgb: // DXGI 1.1
                            pfGuid = WICPixelFormat.Format32bppBGR;
                            sRGB = true;
                            break;

                        default:
                            //Console.WriteLine("ERROR: ScreenGrab does not support all DXGI formats (%u). Consider using DirectXTex.\n", static_cast<uint32_t>(desc.Format));
                            return;
                    }

                    // Screenshots don't typically include the alpha channel of the render target
                    Guid targetGuid = default;
                    switch (textureDesc.Format)
                    {
                        case Vortice.DXGI.Format.R32G32B32A32_Float:
                        case Vortice.DXGI.Format.R16G16B16A16_Float:
                            //if (_IsWIC2())
                            {
                                targetGuid = WICPixelFormat.Format96bppRGBFloat;
                            }
                            //else
                            //{
                            //    targetGuid = WICPixelFormat.Format24bppBGR;
                            //}
                            break;

                        case Vortice.DXGI.Format.R16G16B16A16_UNorm:
                            targetGuid = WICPixelFormat.Format48bppBGR;
                            break;

                        case Vortice.DXGI.Format.B5G5R5A1_UNorm:
                            targetGuid = WICPixelFormat.Format16bppBGR555;
                            break;

                        case Vortice.DXGI.Format.B5G6R5_UNorm:
                            targetGuid = WICPixelFormat.Format16bppBGR565;
                            break;

                        case Vortice.DXGI.Format.R32_Float:
                        case Vortice.DXGI.Format.R16_Float:
                        case Vortice.DXGI.Format.R16_UNorm:
                        case Vortice.DXGI.Format.R8_UNorm:
                        case Vortice.DXGI.Format.A8_UNorm:
                            targetGuid = WICPixelFormat.Format8bppGray;
                            break;

                        default:
                            targetGuid = WICPixelFormat.Format24bppBGR;
                            break;
                    }

                    using var wicFactory = new IWICImagingFactory();
                    //using IWICBitmapDecoder decoder = wicFactory.CreateDecoderFromFileName(path);

                    using Stream stream = File.OpenWrite(path);
                    using IWICStream wicStream = wicFactory.CreateStream(stream);
                    using IWICBitmapEncoder encoder = wicFactory.CreateEncoder(format, wicStream);
                    // Create a Frame encoder
                    var frame = encoder.CreateNewFrame(out var props);
                    frame.Initialize(props);
                    frame.SetSize(textureDesc.Width, textureDesc.Height);
                    frame.SetResolution(72, 72);
                    frame.SetPixelFormat(targetGuid);

                    var context = d3d11GraphicsDevice!.DeviceContext;
                    //var mapped = context.Map(staging, 0, MapMode.Read, MapFlags.None);
                    Span<Color> colors = context.Map<Color>(staging, 0, 0, MapMode.Read, MapFlags.None);

                    // Check conversion
                    if (targetGuid != pfGuid)
                    {
                        // Conversion required to write
                        using (IWICBitmap bitmapSource = wicFactory.CreateBitmapFromMemory(
                            textureDesc.Width,
                            textureDesc.Height,
                            pfGuid,
                            colors))
                        {
                            using (IWICFormatConverter formatConverter = wicFactory.CreateFormatConverter())
                            {
                                if (!formatConverter.CanConvert(pfGuid, targetGuid))
                                {
                                    context.Unmap(staging, 0);
                                    return;
                                }

                                formatConverter.Initialize(bitmapSource, targetGuid, BitmapDitherType.None, null, 0, BitmapPaletteType.MedianCut);
                                frame.WriteSource(formatConverter, new System.Drawing.Rectangle(0, 0, textureDesc.Width, textureDesc.Height));
                            }
                        }
                    }
                    else
                    {
                        // No conversion required
                        int stride = WICPixelFormat.GetStride(pfGuid, textureDesc.Width);
                        frame.WritePixels(textureDesc.Height, stride, colors);
                    }

                    context.Unmap(staging, 0);
                    frame.Commit();
                    encoder.Commit();
                }
            }

19 Source : Util.cs
with MIT License
from anastasios-stamoulis

public static void save_binary_file(float[][] src, string filepath) {
      Console.WriteLine("Saving " + filepath);
      var buffer = new byte[sizeof(float) * src[0].Length];
      using (var writer = new System.IO.BinaryWriter(System.IO.File.OpenWrite(filepath))) {
        for (int row = 0; row < src.Length; row++) {
          System.Buffer.BlockCopy(src[row], 0, buffer, 0, buffer.Length);
          writer.Write(buffer, 0, buffer.Length);
        }
      }
    }

19 Source : VRRecorder.cs
with GNU General Public License v2.0
from andrewjc

public void StopRecording()
        {
            stopTracking = true;
            using (FileStream file = File.OpenWrite(sessionPath + "/" + gameObject.name +".txt"))
            {
                using (StreamWriter sw = new StreamWriter(file))
                {
                    foreach (String str in trackerArray)
                    {
                        sw.WriteLine(str);
                    }
                }
            }
        }

19 Source : Configuration.cs
with GNU General Public License v3.0
from anotak

public bool SaveConfiguration(string filename, string newline, bool whitespace)
		{
			// Kill the file if it exists
			if(File.Exists(filename) == true) File.Delete(filename);
			
			// Open file stream for writing
			FileStream fstream = File.OpenWrite(filename);
			
			// Create output structure and write to file
			string data = OutputConfiguration(newline, whitespace);
			byte[] baData= Encoding.UTF8.GetBytes(data);
			fstream.Write(baData, 0, baData.Length);
			fstream.Flush();
			fstream.Close();
			
			// Return true when done, false when errors occurred
			return !cpErrorResult;
		}

See More Examples