System.IO.File.Create(string)

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

1929 Examples 7

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

public async Task<FileUploadResult> HandleUploadAsync(string fileName, Stream stream)
        {
            replacedertIdenreplacedyProvided(); // Quota is affected
            var fileId = Guid.NewGuid().ToString();
            var targetFile = GetTargetFilePath(fileId);
            var uploadStreamFileSize = stream.Length;

            try
            {
                // Write file (Wait for upload throttle)
                await ServerContext.ServiceTable[_owner]
                    .UploadThrottle.WithResourceAsync(async () =>
                    {
                        using (var destinationStream = File.Create(targetFile))
                        {
                            await stream.CopyToAsync(destinationStream);
                        }
                    });

                // Make sure user has enough space remaining
                if (_owner != null)
                {
                    var lockEntry = ServerContext.ServiceTable[_owner].UserLock;
                    await lockEntry.ObtainExclusiveWriteAsync();
                    var userManager = new WebUserManager(ServerContext);
                    var ownerData = await userManager.FindUserByUsernameAsync(_owner);
                    var afterUploadSpace = ownerData.StorageUsage + uploadStreamFileSize;
                    if (afterUploadSpace > ownerData.StorageQuota)
                    {
                        lockEntry.ReleaseExclusiveWrite();
                        // Throw exception, catch block will remove file and rethrow
                        throw new QuotaExceededException();
                    }
                    // Increase user storage usage
                    ownerData.StorageUsage += uploadStreamFileSize;
                    await userManager.UpdateUserInDatabaseAsync(ownerData);
                    lockEntry.ReleaseExclusiveWrite();
                }
            }
            catch (QuotaExceededException)
            {
                // Roll back write
                await Task.Run(() => File.Delete(targetFile));
                throw;
            }

            return new FileUploadResult
            {
                FileId = fileId,
                Size = uploadStreamFileSize
            };
        }

19 Source : ImageLoading.cs
with GNU General Public License v3.0
from 1330-Studios

public static void SaveToPNG(Sprite s, String name) {
            byte[] b = ImageConversion.EncodeToPNG(s.texture);
            byte[] bytes = new byte[b.Length];

            for (int i = 0; i < b.Length; i++) {
                bytes[i] = b[i];
            }

            File.Create(name).Write(bytes, 0, bytes.Length);
        }

19 Source : FrmRazorTemplates.cs
with MIT License
from 2881099

private void buttonX1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBoxX1.Text))
            {
                ToastNotification.ToastBackColor = Color.Red;
                ToastNotification.ToastForeColor = Color.White;
                ToastNotification.ToastFont = new Font("微软雅黑", 15);
                ToastNotification.Show(this, "模版名称不允许为空", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
                return;
            }
            string path = Path.Combine(Environment.CurrentDirectory, "Templates");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            TemplatesName = textBoxX1.Text;
            TemplatesPath = Path.Combine(path, $"{textBoxX1.Text}.tpl");
            if (File.Exists(TemplatesPath))
            {
                ToastNotification.ToastBackColor = Color.Red;
                ToastNotification.ToastForeColor = Color.White;
                ToastNotification.ToastFont = new Font("微软雅黑", 15);
                ToastNotification.Show(this, "模版名称己存在", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
                return;
            }
            using (var sr = File.Create(TemplatesPath))
            {
                sr.Close();
                sr.Dispose();
            }
            this.Close();
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

19 Source : FileManager.cs
with GNU General Public License v3.0
from 2dust

public static void UncompressFile(string fileName, byte[] content)
        {
            try
            {
                // Because the uncompressed size of the file is unknown,
                // we are using an arbitrary buffer size.
                byte[] buffer = new byte[4096];
                int n;

                using (FileStream fs = File.Create(fileName))
                using (GZipStream input = new GZipStream(new MemoryStream(content),
                        CompressionMode.Decompress, false))
                {
                    while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fs.Write(buffer, 0, n);
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
        }

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

public static void ExistsOrCreateFile(string path)
            {
                if (!File.Exists(path))
                {
                    File.Create(path);
                }
            }

19 Source : Log.LogFile.partial.cs
with MIT License
from 7Bytes-Studio

public static void SetLogFileMode(string logFilePath,int writePeriod)
        {
            s_LogFilePath = logFilePath;
            if (!string.IsNullOrEmpty(s_LogFilePath))
            {
                if (!File.Exists(s_LogFilePath))
                {
                    File.Create(s_LogFilePath);
                }            
            }
            else
            {
                return;
            }

            s_WritePeriod = writePeriod;
            if (0 >= s_WritePeriod)
            {
                throw new System.ArgumentException("'writePeriod'不能小于0。推荐数值为5000(即5s)");
            }

            s_LogFileMode = true;
            CuttingLine();
            s_Timer = new System.Threading.Timer(TimerCallback, null, 0, s_WritePeriod);

        }

19 Source : KissMangaDownload.cs
with GNU General Public License v3.0
from 9vult

public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();

            string mName = chapter.GetChapterRoot().Parent.Name;
            string cUrl = "https://kissmanga.org/chapter/" + mName + "/" + chapter.GetID();
            string[] pageUrls = KissMangaHelper.GetPageUrls(cUrl);        
            
            foreach (string url in pageUrls)
            {
                string imgFile = Path.Combine(chapter.GetChapterRoot().FullName, KissMangaHelper.GetPageFileName(url));
                DownloadAsync(new Uri(url), imgFile);
            }
        }

19 Source : MangaDexDownload.cs
with GNU General Public License v3.0
from 9vult

public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
            string jsonUrl = MangaDexHelper.MANGADEX_URL + "/api/chapter/" + chapter.GetID();
            string jsonString;

            using (var wc = new WebClient())
            {
                jsonString = wc.DownloadString(jsonUrl);
            }

            JObject jobj = JObject.Parse(jsonString);

            string server = (string)jobj["server"];
            string hash = (string)jobj["hash"];

            // string[] page_array = /* ((string) */ jobj["page_array"]. /* ).Split(',') */;
            List<string> page_array = new List<string>();
            IJEnumerable<JToken> jtokens = jobj["page_array"].Values();
            foreach(JToken t in jtokens)
            {
                page_array.Add((string)t);
            }

            foreach (string file in page_array)
            {
                if (server == "/data/")
                    server = MangaDexHelper.MANGADEX_URL + "/data/";

                string imgUrl = server + hash + "/" + file;

                FileInfo imgFile = new FileInfo(
                    Path.Combine(
                        chapter.GetChapterRoot().FullName, 
                        ConvertToNumericFileName(file)
                ));

                if (File.Exists(imgFile.FullName))
                    if (imgFile.Length <= 0)
                        File.Delete(imgFile.FullName);

                DownloadAsync(new Uri(imgUrl), imgFile.FullName);
            }
        }

19 Source : NhentaiDownload.cs
with GNU General Public License v3.0
from 9vult

public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
            List<HtmlDoreplacedent> docs = new List<HtmlDoreplacedent>();
            int pageCount = NhentaiHelper.GetPageCount("https://nhentai.net/g/" + chapter.GetID());

            string hUrl = "https://nhentai.net/g/" + chapter.GetID() + "/";

            string baseUrl = NhentaiHelper.GetImageUrl(hUrl + "1");
            string hash = NhentaiHelper.GetHash(baseUrl);
            
            for (int page = 1; page <= pageCount; page++)
            {
                string imgUrl = NhentaiHelper.ImgBase() + hash + "/" + page + "." + NhentaiHelper.GetExt(baseUrl);
                string imgFile = Path.Combine(chapter.GetChapterRoot().FullName, page + "." + NhentaiHelper.GetExt(baseUrl));
                DownloadAsync(new Uri(imgUrl), imgFile);
            }
        }

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

public IEnumerator Dump(string sceneName = null)
		{

			List<string> scenes = new List<string>();
			for (int j = 0; j < USceneManager.sceneCountInBuildSettings; j++)
			{
				string scenePath = SceneUtility.GetScenePathByBuildIndex(j);
				string name = Path.GetFileNameWithoutExtension(scenePath);
				scenes.Add(name);
				var load = USceneManager.LoadSceneAsync(j, LoadSceneMode.Single);
				while (!load.isDone)
				{
					yield return new WaitForEndOfFrame();
				}
				yield return new WaitForSeconds(0.2f);
				Scene s = USceneManager.GetActiveScene();
				StringBuilder sb = new StringBuilder();
				foreach (var g in s.GetRootGameObjects())
                {
					Visit(g.transform, 0, null,sb);
                }
				try
				{
					var fs = File.Create($"Z:\\1\\{s.name}.txt");
					StreamWriter sw = new StreamWriter(fs);
					sw.Write(sb.ToString());
					sw.Close();
					fs.Close();
				}
				catch { }
				
				//
			}
			var load_ = USceneManager.LoadSceneAsync(2, LoadSceneMode.Single);
			while (!load_.isDone)
			{
				yield return new WaitForEndOfFrame();
			}
			yield return USceneManager.LoadSceneAsync("Quit_To_Menu");
			while (USceneManager.GetActiveScene().name != Constants.MENU_SCENE)
			{
				yield return new WaitForEndOfFrame();
			}

			
			
		}

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

public static void SaveSceneSettings(object data,string sceneName)
        {
            string dir = Path.Combine(DATA_DIR, sceneName+".json");

            using (FileStream fileStream = File.Create(dir))
            {
                using (var writer = new StreamWriter(fileStream))
                {
                    try
                    {
                        writer.Write
                        (
                            JsonConvert.SerializeObject
                            (
                                data,
                                Formatting.Indented,
                                new JsonSerializerSettings
                                {
                                    TypeNameHandling = TypeNameHandling.Auto,
                                }
                            )
                        );
                    }
                    catch (Exception e)
                    {
                        LogError(e);
                    }
                }
            }
        }

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

public static void SaveGlobalSettings(object data)
        {
            var settings = data;

            if (settings is null)
                return;

            //Log("Saving Global Settings");

            if (File.Exists(GLOBAL_FILE_DIR + ".bak"))
            {
                File.Delete(GLOBAL_FILE_DIR + ".bak");
            }

            if (File.Exists(GLOBAL_FILE_DIR))
            {
                File.Move(GLOBAL_FILE_DIR, GLOBAL_FILE_DIR + ".bak");
            }

            using (FileStream fileStream = File.Create(GLOBAL_FILE_DIR))
            {
                using (var writer = new StreamWriter(fileStream))
                {
                    try
                    {
                        writer.Write
                        (
                            JsonConvert.SerializeObject
                            (
                                settings,
                                Formatting.Indented,
                                new JsonSerializerSettings
                                {
                                    TypeNameHandling = TypeNameHandling.Auto,
                                }
                            )
                        );
                    }
                    catch (Exception e)
                    {
                        LogError(e);
                    }
                }
            }

            

            
        }

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

public static void FileSynchronization(string modsDir, ModelModsFiles serverFiles)
        {
            restoreFolderTree(modsDir, serverFiles.FoldersTree);

            foreach (var serverFile in serverFiles.Files)
            {
                var fullName = Path.Combine(modsDir, serverFile.FileName);
                // Имя присутствует в списке, файл необходимо будет удалить ( или заменить)
                if (File.Exists(fullName))
                {
                    File.Delete(fullName);
                }

                if (serverFile.Hash == null)
                {
                    continue;
                }


                // Create the file, or overwrite if the file must exist.
                using (FileStream fs = File.Create(fullName))
                {
                    Loger.Log("Restore: " + fullName);

                    if (serverFile.Hash.Length > 0)
                    {
                        fs.Write(serverFile.Hash, 0, serverFile.Hash.Length);
                    }
                }
            }
        }

19 Source : MixedRealityToolkitFiles.cs
with Apache License 2.0
from abist-co-ltd

private static void TryToCreateGeneratedFolder()
        {
            // Always add the MixedRealityToolkit.Generated folder to replacedets
            var generatedDirs = GetDirectories(MixedRealityToolkitModuleType.Generated);
            if (generatedDirs == null || !generatedDirs.Any())
            {
                string generatedFolderPath = Path.Combine("replacedets", "MixedRealityToolkit.Generated");
                if (!Directory.Exists(generatedFolderPath))
                {
                    Directory.CreateDirectory(generatedFolderPath);
                }

                string generatedSentinelFilePath = Path.Combine(generatedFolderPath, "MRTK.Generated.sentinel");
                if (!File.Exists(generatedSentinelFilePath))
                {
                    // Make sure we create and dispose/close the filestream just created
                    using (var f = File.Create(generatedSentinelFilePath)) { }
                }

                TryRegisterModuleViaFile(generatedSentinelFilePath);
            }
        }

19 Source : AutomationTestBase.cs
with MIT License
from ABTSoftware

public void SaveToBmp(string fileName, WriteableBitmap bmp)
        {
            BmpBitmapEncoder bmpEncoder = new BmpBitmapEncoder();
            //pngEncoder.Palette = new BitmapPalette(bmp, int.MaxValue);
            bmpEncoder.Frames.Add(BitmapFrame.Create(bmp));

            using (var fileStream = File.Create(fileName))
            {
                bmpEncoder.Save(fileStream);
            }
        }

19 Source : AutomationTestBase.cs
with MIT License
from ABTSoftware

public void SaveToPng(string fileName, WriteableBitmap bmp)
        {
            var path = Path.GetDirectoryName(fileName);

            if (!string.IsNullOrEmpty(path))
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
                //pngEncoder.Palette = new BitmapPalette(bmp, int.MaxValue);
                pngEncoder.Frames.Add(BitmapFrame.Create(bmp));

                using (var fileStream = File.Create(fileName))
                {
                    pngEncoder.Save(fileStream);
                }
            }
        }

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

[Fact]
        public void Can_use_Mashup_Packaging_API()
        {
            using (var pbixSrc = GetEmbeddedResourceStream("Simple.pbix"))
            using (var tmp = new TempFolder())
            {
                var pbixPath = Path.Combine(tmp.Path, "Simple.pbix");
                using (var dest = File.Create(pbixPath))
                {
                    pbixSrc.CopyTo(dest);
                }

                using (var reader = new PowerBI.PbixReader(pbixPath, _fixture.DependenciesResolver))
                using (var extractor = new PbixExtractAction(reader))
                {
                    extractor.ExtractMashup(new ProjectSystem.MashupSettings { SerializationMode = ProjectSystem.MashupSerializationMode.Expanded }); // This one will require to load the Mashup.Packaging dll
                }

                // Double-check that the M script has actually be extracted
                replacedert.True(File.Exists(Path.Combine(
                    Path.GetDirectoryName(pbixPath),
                    Path.GetFileNameWithoutExtension(pbixPath),
                    "Mashup",
                    "Package",
                    "Formulas",
                    "Section1.m",
                    "Query1.m")));
            }
        }

19 Source : FileCommandManager.cs
with MIT License
from actions

public void InitializeFiles(IExecutionContext context, ContainerInfo container)
        {
            var oldSuffix = _fileSuffix;
            _fileSuffix = Guid.NewGuid().ToString();
            foreach (var fileCommand in _commandExtensions)
            {
                var oldPath = Path.Combine(_fileCommandDirectory, fileCommand.FilePrefix + oldSuffix);
                if (oldSuffix != String.Empty && File.Exists(oldPath))
                {
                    TryDeleteFile(oldPath);
                }

                var newPath = Path.Combine(_fileCommandDirectory, fileCommand.FilePrefix + _fileSuffix);
                TryDeleteFile(newPath);
                File.Create(newPath).Dispose();

                var pathToSet = container != null ? container.TranslateToContainerPath(newPath) : newPath; 
                context.SetGitHubContext(fileCommand.ContextName, pathToSet);
            }
        }

19 Source : StreamVideoSourceHandler.cs
with MIT License
from adamfisher

public async Task<string> LoadVideoAsync(VideoSource source, CancellationToken cancellationToken = default(CancellationToken))
        {
            string path = null;
            var streamVideoSource = source as StreamVideoSource;

            if (streamVideoSource?.Stream != null)
            {
                using (var stream = await streamVideoSource.GetStreamAsync(cancellationToken).ConfigureAwait(false))
                {
                    if (stream != null)
                    {
                        var tempFileName = GetFileName(stream, streamVideoSource.Format);
                        var tempDirectory = Path.Combine(Path.GetTempPath(), "MediaCache");
                        path = Path.Combine(tempDirectory, tempFileName);

                        if (!File.Exists(path))
                        {
                            if (!Directory.Exists(tempDirectory))
                                Directory.CreateDirectory(tempDirectory);

                            using (var tempFile = File.Create(path))
                            {
                                await stream.CopyToAsync(tempFile);
                            }
                        }
                    }
                }
            }

            return path;
        }

19 Source : FileManager.cs
with GNU General Public License v3.0
from AdamMYoung

public static void SaveGroups(List<GroupViewModel> groups)
        {
            if (groups.Count == 0)
                return;

            var writer = new XmlSerializer(typeof(List<GroupViewModel>));
            var file = File.Create(GroupsFile);

            writer.Serialize(file, groups);
            file.Close();
        }

19 Source : PersistSequentialModel.cs
with MIT License
from adamtiger

public static void SerializeModel(SequentialModel model, string fileName)
        {
            Stream stream = File.Create(fileName);
            BinaryFormatter serializer = new BinaryFormatter();
            serializer.Serialize(stream, model);
            stream.Close();
        }

19 Source : AudioFile.cs
with MIT License
from adlez27

public void Write (byte[] data, string destination)
        {
            var format = new WaveFormat(44100,16,1);
            using (FileStream fs = File.Create(destination))
            using (WaveFileWriter wfw = new WaveFileWriter(fs, format))
            {
                wfw.Write(data,data.Length);
            }
        }

19 Source : ClonesManager.cs
with MIT License
from adrenak

private static void RegisterClone(Project cloneProject)
        {
            /// Add clone identifier file.
            string identifierFile = Path.Combine(cloneProject.projectPath, ClonesManager.CloneFileName);
            File.Create(identifierFile).Dispose();

            //Add argument file with default argument
            string argumentFilePath = Path.Combine(cloneProject.projectPath, ClonesManager.ArgumentFileName);
            File.WriteAllText(argumentFilePath, DefaultArgument, System.Text.Encoding.UTF8);

            /// Add collabignore.txt to stop the clone from messing with Unity Collaborate if it's enabled. Just in case.
            string collabignoreFile = Path.Combine(cloneProject.projectPath, "collabignore.txt");
            File.WriteAllText(collabignoreFile, "*"); /// Make it ignore ALL files in the clone.
        }

19 Source : SimpleAudioPlayerImplementation.cs
with MIT License
from adrianstevens

public bool Load(Stream audioStream)
        {
            player.Reset();

            DeleteFile(path);

            //cache to the file system
            path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), $"cache{index++}.wav");
            var fileStream = File.Create(path);
            audioStream.CopyTo(fileStream);
            fileStream.Close();

            try
            {
                player.SetDataSource(path);
            }
            catch
            {
                try
                {
                    var context = Android.App.Application.Context;
                    player?.SetDataSource(context, Uri.Parse(Uri.Encode(path)));
                }
                catch
                {
                    return false;
                }
            }

            return PreparePlayer();
        }

19 Source : CompilationServices.cs
with MIT License
from adrianoc

private static string InternalCompile(string targetPath, string source, bool exe, params string[] references)
        {
            var targetFolder = Path.GetDirectoryName(targetPath);
            if (!Directory.Exists(targetFolder))
            {
                Directory.CreateDirectory(targetFolder);
            }

            var hash = BitConverter.ToString(SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(source))).Replace("-", "");
            var outputFilePath = $"{targetPath}-{hash}.{(exe ? "exe" : "dll")}";
            if (File.Exists(outputFilePath))
            {
                return outputFilePath;
            }

            var syntaxTree = SyntaxFactory.ParseSyntaxTree(SourceText.From(source), new CSharpParseOptions());

            var compilationOptions = new CSharpCompilationOptions(
                exe ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: OptimizationLevel.Release,
                allowUnsafe: true);

            var compilation = CSharpCompilation.Create(
                Path.GetFileNameWithoutExtension(outputFilePath),
                new[] {syntaxTree},
                references.Select(r => MetadataReference.CreateFromFile(r)).ToArray(),
                compilationOptions);

            var diagnostics = compilation.GetDiagnostics();
            if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
            {
                throw new Exception(diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Aggregate("", (acc, curr) => acc + "\r\n" + curr.ToString()) + "\r\n\r\n" + source);
            }

            using (var outputreplacedembly = File.Create(outputFilePath))
            {
                compilation.Emit(outputreplacedembly);
            }

            return outputFilePath;
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private void GameLoop_SaveLoaded(object sender, StardewModdingAPI.Events.SaveLoadedEventArgs e)
        {
            if (config.CustomMailbox)
            {
                try
                {
                    Texture2D tex = new Texture2D(Game1.graphics.GraphicsDevice, 16, 32);
                    Color[] data = new Color[tex.Width * tex.Height];
                    tex.GetData(data);

                    Texture2D source = Helper.Content.Load<Texture2D>($"Maps/{Game1.currentSeason.ToLower()}_outdoorsTileSheet", ContentSource.GameContent);
                    Color[] srcData = new Color[source.Width * source.Height];
                    source.GetData(srcData);

                    int width = 400;
                    int startx = 80;
                    int starty = 1232;
                    int start = starty * width + startx;
                    for (int i = 0; i < data.Length; i++)
                    {
                        int srcIdx = start + (i / 16 * width + i % 16); 
                        data[i] = srcData[srcIdx];
                    }
                    tex.SetData(data);
                    Stream stream = File.Create(Path.Combine(Helper.DirectoryPath, "json-replacedets", "BigCraftables", "Mailbox", "big-craftable.png"));
                    tex.SaveAsPng(stream, tex.Width, tex.Height);
                    stream.Close();
                    Monitor.Log($"Wrote custom mailbox texture from Maps/{ Game1.currentSeason.ToLower()}_outdoorsTileSheet to {Path.Combine(Helper.DirectoryPath, "json-replacedets", "BigCraftables", "Mailbox", "big-craftable.png")}.", LogLevel.Debug);
                    Helper.Content.InvalidateCache("Tilesheets/Craftables");
                }
                catch (Exception ex)
                {
                    Monitor.Log($"Error writing mailbox texture.\n{ex}", LogLevel.Warn);
                }
            }

            Farm farm = Game1.getFarm();
            foreach (KeyValuePair<Vector2, Object> kvp in farm.objects.Pairs)
            {
                if (kvp.Value.Name.EndsWith("Mailbox"))
                {
                    (farm as Farm).mapMainMailboxPosition = Utility.Vector2ToPoint(kvp.Key);
                    PMonitor.Log($"Set mailbox location to {kvp.Key}");
                    return;
                }
            }
            farm.mapMainMailboxPosition = Point.Zero;
            PMonitor.Log("Set mailbox location to 0,0");
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public override void Entry(IModHelper helper)
        {
            context = this;
            Config = Helper.ReadConfig<ModConfig>();
            if (!Config.EnableMod)
                return;
            helper.Events.GameLoop.GameLaunched += GameLoop_GameLaunched;
            helper.Events.GameLoop.DayStarted += GameLoop_DayStarted;
            helper.Events.Player.Warped += Player_Warped;

            var harmony = HarmonyInstance.Create(ModManifest.UniqueID);

            harmony.Patch(
               original: AccessTools.Method(typeof(Object), nameof(Object.placementAction)),
               postfix: new HarmonyMethod(typeof(ModEntry), nameof(placementAction_Postfix))
            );

            harmony.Patch(
               original: AccessTools.Method(typeof(Object), nameof(Object.performRemoveAction)),
               postfix: new HarmonyMethod(typeof(ModEntry), nameof(performRemoveAction_Postfix))
            );
            harmony.Patch(
               original: AccessTools.Method(typeof(Object), nameof(Object.checkForAction)),
               prefix: new HarmonyMethod(typeof(ModEntry), nameof(checkForAction_Prefix))
            );
            harmony.Patch(
               original: AccessTools.Method(typeof(Object), nameof(Object.isPreplacedable)),
               prefix: new HarmonyMethod(typeof(ModEntry), nameof(Object_isPreplacedable_Prefix))
            );

            if (Config.LoadCustomTerrarium)
            {
                try
                {
                    string path = Directory.GetParent(helper.DirectoryPath).GetDirectories().Where(f => f.FullName.EndsWith("[CP] Lively Frog Sanctuary")).FirstOrDefault()?.FullName;
                    if (path != null)
                    {
                        Texture2D tex = new Texture2D(Game1.graphics.GraphicsDevice, 48, 48);
                        Color[] data = new Color[tex.Width * tex.Height];
                        tex.GetData(data);

                        FileStream setStream = File.Open(Path.Combine(path, "replacedets", "frog-vivarium.png"), FileMode.Open);
                        Texture2D source = Texture2D.FromStream(Game1.graphics.GraphicsDevice, setStream);
                        setStream.Dispose();
                        Color[] srcData = new Color[source.Width * source.Height];
                        source.GetData(srcData);

                        for (int i = 0; i < srcData.Length; i++)
                        {
                            if (data.Length <= i + 48 * 12)
                                break;
                            data[i + 48 * 12] = srcData[i];
                        }
                        tex.SetData(data);
                        string outDir = Directory.GetParent(helper.DirectoryPath).GetDirectories().Where(f => f.FullName.EndsWith("[BC] Terrarium")).FirstOrDefault()?.FullName;
                        Stream stream = File.Create(Path.Combine(outDir, "replacedets", "terrarium.png"));
                        tex.SaveAsPng(stream, tex.Width, tex.Height);
                        stream.Dispose();
                        Monitor.Log("Terrarium overwritten with lively frog sanctuary", LogLevel.Debug);
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log($"Can't load lively frog sanctuary for Terrarium\n{ex}", LogLevel.Error);
                }
            }
        }

19 Source : Platform.cs
with Mozilla Public License 2.0
from agebullhu

private static bool ExtractManifestResource(string resourceName, string outputPath)
		{
			if (File.Exists(outputPath))
			{
				// This is necessary to prevent access conflicts if multiple processes are run from the
				// same location. The naming scheme implemented in UnmanagedLibrary should ensure that
				// the correct version is always used.
				return true;
			}

			Stream resourceStream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream(resourceName);

			if (resourceStream == null)
			{
				// No manifest resources were compiled into the current replacedembly. This is likely a 'manual
				// deployment' situation, so do not throw an exception at this point and allow all deployment
				// paths to be searched.
				return false;
			}

			try
			{
				using (FileStream fileStream = File.Create(outputPath))
				{
					resourceStream.CopyTo(fileStream);
				}
			}
			catch (UnauthorizedAccessException)
			{
				// Caller does not have write permission for the current file
				return false;
			}

			return true;
		}

19 Source : IconFile.cs
with MIT License
from ahopper

static public void SaveToICO(Drawing drawing, List<int> sizes, string filename)
        {
            int headerLen = 6 + sizes.Count * 16;
            using (var icoStream = new MemoryStream())
            {
                //write ICONDIR
                icoStream.WriteByte(0);
                icoStream.WriteByte(0);
                icoStream.WriteByte(1);
                icoStream.WriteByte(0);
                icoStream.WriteByte((byte)sizes.Count);
                icoStream.WriteByte(0);
                
                icoStream.Position = headerLen;
                
                for (int i =0; i< sizes.Count; i++)
                {
                    var start = icoStream.Position;
                    SaveDrawing(drawing, sizes[i], icoStream);
                    var end = icoStream.Position;
                    int pngLen = (int)(end - start);
               
                    icoStream.Position = 6 + i * 16;
                    icoStream.WriteByte((byte)sizes[i]);
                    icoStream.WriteByte((byte)sizes[i]);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(32);

                    icoStream.WriteByte((byte)(pngLen & 0xff));
                    icoStream.WriteByte((byte)((pngLen >> 8) & 0xff)); 
                    icoStream.WriteByte((byte)((pngLen >> 16) & 0xff));
                    icoStream.WriteByte((byte)(pngLen >> 24));
                   
                    icoStream.WriteByte((byte)(start & 0xff)); 
                    icoStream.WriteByte((byte)((start >> 8) & 0xff));
                    icoStream.WriteByte((byte)((start >> 16) & 0xff));
                    icoStream.WriteByte((byte)(start >> 24));
           
                    icoStream.Position=end;
                }
                using(var icoFile=File.Create(filename))
                {
                    icoFile.Write(icoStream.GetBuffer(), 0, (int)icoStream.Position);
                }
            }
        }

19 Source : IconFile.cs
with MIT License
from ahopper

static public void SaveToICNS(Drawing drawing, List<int> sizes, string filename)
        {
            int headerLen = 8;
            int fileLen = headerLen;
            using (var icoStream = new MemoryStream())
            {
                icoStream.WriteByte(0x69);
                icoStream.WriteByte(0x63);
                icoStream.WriteByte(0x6e);
                icoStream.WriteByte(0x73);
                
                icoStream.Position = headerLen;

                for (int i = 0; i < sizes.Count; i++)
                {
                    var start = icoStream.Position;
                    icoStream.Position += 8;
                    SaveDrawing(drawing, sizes[i], icoStream);
                    var end = icoStream.Position;
                    int pngLen = (int)(end - start);
                    fileLen += pngLen;

                    icoStream.Position = start;
                    string iconType;
                    switch(sizes[i])
                    {
                        case 16: iconType = "icp4"; break;
                        case 32: iconType = "icp5"; break;
                        case 64: iconType = "icp6"; break;
                        case 128: iconType = "ic07"; break;
                        case 256: iconType = "ic08"; break;
                        case 512: iconType = "ic09"; break;
                        default: throw new Exception($"Unsupported icns size {sizes[i]}");
                    }
                    icoStream.Write(ASCIIEncoding.ASCII.GetBytes(iconType));

                    icoStream.WriteByte((byte)(pngLen >> 24));
                    icoStream.WriteByte((byte)((pngLen >> 16) & 0xff));
                    icoStream.WriteByte((byte)((pngLen >> 8) & 0xff));
                    icoStream.WriteByte((byte)(pngLen & 0xff));
                    
                    icoStream.Position = end;
                }
                icoStream.Position = 4;

                icoStream.WriteByte((byte)(fileLen >> 24));
                icoStream.WriteByte((byte)((fileLen >> 16) & 0xff));
                icoStream.WriteByte((byte)((fileLen >> 8) & 0xff));
                icoStream.WriteByte((byte)(fileLen & 0xff));
                
                using (var icoFile = File.Create(filename))
                {
                    icoFile.Write(icoStream.GetBuffer(), 0, fileLen);
                }
            }
        }

19 Source : IconFile.cs
with MIT License
from ahopper

static public void SaveToPNG(Drawing drawing, int size, string filename)
        {
            using (var icoFile = File.Create(filename))
            {
                SaveDrawing(drawing, size, icoFile);
            }
        }

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

public virtual void Save(string filePath, bool x64, bool UTF32) {
			var f = File.Create(filePath);
			Save(f, x64, UTF32);
			f.Close();
		}

19 Source : Patch.cs
with MIT License
from AkiniKites

public void AddFile(Stream source, string filePath, bool overwrite = false)
        {
            var subPath = NormalizeSubPath(filePath);
            var path = Path.Combine(WorkingDir, subPath);

            if (Files.Contains(subPath) && !overwrite)
                throw new PatchException($"Attempted to add duplicate file to patch: {subPath}");

            Paths.CheckDirectory(Path.GetDirectoryName(path));
            using var fs = File.Create(path);
            source.CopyTo(fs);

            Files.Add(subPath);
        }

19 Source : GvrCompatibilityChecker.cs
with MIT License
from alanplotko

private static void ImportBackwardsCompatibilityPackage() {
    int option = EditorUtility.DisplayDialogComplex(IMPORT_REQUIRED_replacedLE,
      IMPORT_REQUIRED_MESSAGE,
      IMPORT_PACKAGE_BUTTON,
      CANCEL_DO_NOT_CHECK_AGAIN_BUTTON,
      CANCEL_BUTTON);

    switch (option) {
      case 0: // Import the package.
        string packagePath = Application.dataPath + BACK_COMPAT_PACKAGE_PATH;
        if (File.Exists(IGNORE_MANIFEST_MERGE_CHECK_PATH)) {
          File.Delete(IGNORE_MANIFEST_MERGE_CHECK_PATH);
        }

        if (!File.Exists(packagePath)) {
          EditorUtility.DisplayDialog(PACKAGE_NOT_FOUND_replacedLE, null, OK_BUTTON);
          return;
        }
        replacedetDatabase.ImportPackage(packagePath, true);
        replacedetDatabase.Refresh();
        AndroidManifestCompatibilityUpdate();
        return;

      case 1: // Do not import, and do not check again.
        File.Create(IGNORE_COMPATIBILITY_CHECK_PATH);
        File.Create(IGNORE_MANIFEST_MERGE_CHECK_PATH);
        EditorUtility.DisplayDialog(REENABLE_COMPATIBILITY_CHECK_replacedLE,
          REENABLE_COMPATIBILITY_CHECK_MESSAGE, OK_BUTTON);
        AndroidManifestCompatibilityUpdate();
        return;

      case 2: // Do not import.
        // Fall through.
      default:
        return;
    }
  }

19 Source : GvrCompatibilityChecker.cs
with MIT License
from alanplotko

private static void AndroidManifestCompatibilityUpdate() {
#if !UNITY_HAS_GOOGLEVR
    if (File.Exists(PLUGINS_ANDROID_PATH + ANDROID_MANIFEST)) {
      // Show warning dialog.
      EditorUtility.DisplayDialog(MANIFEST_UPDATE_WARNING_replacedLE,
          MERGE_MANIFEST_WARNING_MESSAGE, OK_BUTTON);
    } else {
      FileUtil.CopyFileOrDirectory(PLUGINS_ANDROID_PATH + ANDROID_MANIFEST_CARDBOARD,
          PLUGINS_ANDROID_PATH + ANDROID_MANIFEST);
    }
#else
    if (!File.Exists(IGNORE_MANIFEST_MERGE_CHECK_PATH) &&
        File.Exists(PLUGINS_ANDROID_PATH + ANDROID_MANIFEST)) {
      EditorUtility.DisplayDialog(MANIFEST_UPDATE_WARNING_replacedLE,
          UNMERGE_MANIFEST_WARNING_MESSAGE, OK_BUTTON);
    }
#endif  // UNITY_HAS_GOOGLEVR
    File.Create(IGNORE_MANIFEST_MERGE_CHECK_PATH);
  }

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 : Ring0.cs
with MIT License
from AlexGyver

private static string GetTempFileName() {
      
      // try to create one in the application folder
      string location = Getreplacedembly().Location;
      if (!string.IsNullOrEmpty(location)) {        
        try {
          string fileName = Path.ChangeExtension(location, ".sys");
          using (FileStream stream = File.Create(fileName)) {
            return fileName;
          }
        } catch (Exception) { }
      }

      // if this failed, try to get a file in the temporary folder
      try {
        return Path.GetTempFileName();        
      } catch (IOException) { 
          // some I/O exception
      } 
      catch (UnauthorizedAccessException) { 
        // we do not have the right to create a file in the temp folder
      }
      catch (NotSupportedException) {
        // invalid path format of the TMP system environment variable
      }
     
      return null;
    }

19 Source : MainWindow.xaml.cs
with Apache License 2.0
from AlexWan

private bool CheckWorkWithDirectory()
        {
            try
            {

                if (!Directory.Exists("Engine"))
                {
                    Directory.CreateDirectory("Engine");
                }

                if (File.Exists("Engine\\checkFile.txt"))
                {
                    File.Delete("Engine\\checkFile.txt");
                }

                File.Create("Engine\\checkFile.txt");

                if (File.Exists("Engine\\checkFile.txt") == false)
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }


            return true;
        }

19 Source : OsConverterMaster.cs
with Apache License 2.0
from AlexWan

private void WorkerSpace()
        {
            if (string.IsNullOrWhiteSpace(_sourceFile))
            {
                SendNewLogMessage(OsLocalization.Converter.Message2, LogMessageType.System);
                return;
            }
            else if (string.IsNullOrWhiteSpace(_exitFile))
            {
                SendNewLogMessage(OsLocalization.Converter.Message3, LogMessageType.System);
                return;
            }

            if (!File.Exists(_exitFile))
            {
                File.Create(_exitFile);
            }

            StreamReader reader = new StreamReader(_sourceFile);

            SendNewLogMessage(OsLocalization.Converter.Message4, LogMessageType.System);

            SendNewLogMessage(OsLocalization.Converter.Message5, LogMessageType.System);

            List<Trade> trades = new List<Trade>();

            int currentWeek = 0;

            bool isNotFirstTime = false;

            try
            {
                while (!reader.EndOfStream)
                {
                    Trade trade = new Trade();
                    trade.SetTradeFromString(reader.ReadLine());

                    int partMonth = 1;

                    if (trade.Time.Day <= 10)
                    {
                        partMonth = 1;
                    }
                    else if (trade.Time.Day > 10 &&
                        trade.Time.Day < 20)
                    {
                        partMonth = 2;
                    }

                    else if (trade.Time.Day >= 20)
                    {
                        partMonth = 3;
                    }

                    if (currentWeek == 0)
                    {

                        SendNewLogMessage(
                            OsLocalization.Converter.Message6 + partMonth +
                            OsLocalization.Converter.Message7 + trade.Time.Month, LogMessageType.System);
                        currentWeek = partMonth;
                    }


                    if (partMonth != currentWeek || reader.EndOfStream)
                    {
                        SendNewLogMessage(OsLocalization.Converter.Message6 + currentWeek +
                                          OsLocalization.Converter.Message7 + trade.Time.Month +
                                          OsLocalization.Converter.Message8, LogMessageType.System);

                        TimeFrameBuilder timeFrameBuilder = new TimeFrameBuilder();
                        timeFrameBuilder.TimeFrame = TimeFrame;

                        CandleSeries series = new CandleSeries(timeFrameBuilder, new Security() { Name = "Unknown" },StartProgram.IsOsConverter);

                        series.IsStarted = true;

                        series.SetNewTicks(trades);

                        List<Candle> candles = series.CandlesAll;

                        if (candles == null)
                        {
                            continue;
                        }

                        StreamWriter writer = new StreamWriter(_exitFile, isNotFirstTime);

                        for (int i = 0; i < candles.Count; i++)
                        {
                            writer.WriteLine(candles[i].StringToSave);
                        }

                        writer.Close();

                        SendNewLogMessage(OsLocalization.Converter.Message9, LogMessageType.System);

                        isNotFirstTime = true;

                        trades = new List<Trade>();
                        series.Clear();

                        currentWeek = partMonth;

                        SendNewLogMessage(OsLocalization.Converter.Message6 + partMonth +
                                          OsLocalization.Converter.Message7 + trade.Time.Month, LogMessageType.System);
                    }
                    else
                    {
                        trades.Add(trade);
                    }
                }
            }
            catch (Exception error)
            {
                SendNewLogMessage(OsLocalization.Converter.Message10, LogMessageType.System);
                SendNewLogMessage(error.ToString(), LogMessageType.Error);
                reader.Close();
                return;
            }

            reader.Close();



            SendNewLogMessage(OsLocalization.Converter.Message9, LogMessageType.System);
        }

19 Source : Program.cs
with MIT License
from Alexx999

private static void Dump(SafeProcessHandle process, string outFileName, IntPtr address, IntPtr length, bool unprotect)
        {
            using (var file = File.Create(outFileName))
            {
                IntPtr read;
                using (var mmf = MemoryMappedFile.CreateFromFile(file, null, length.ToInt64(), MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.None, true))
                using (var accessor = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Write))
                {
                    var buffer = (SafeBuffer) accessor.SafeMemoryMappedViewHandle;
                    var ptr = buffer.DangerousGetHandle();
                    if (!ReadProcessMemory(process.DangerousGetHandle(), address, ptr, length, out read))
                    {
                        var error = Marshal.GetLastWin32Error();
                        Console.WriteLine($"Reading process memory failed with error 0x{error:8X}");
                        if (error == 299 && !unprotect)
                        {
                            Console.WriteLine("You can try -unprotect option");
                        }
                    }
                }

                if (read != length)
                {
                    Console.WriteLine($"Data was read partially - {read.ToInt64()} bytes out of {length.ToInt64()} bytes requested");
                    file.SetLength(read.ToInt64());
                }
            }
        }

19 Source : FileProvider.cs
with MIT License
from alfa-laboratory

public bool Create(string filename, string path, string content)
        {
            try
            {
                var fullpath = Path.Combine(path, filename);
                var file = System.IO.File.Create(fullpath);
                file.Close();
                if (!Exist(fullpath)) return false;
                Log.Logger().LogInformation($"An empty file \"{filename}\" in the \"{fullpath}\" directory has been created");
                return true;

            }
            catch (FileNotFoundException e)
            {
                Log.Logger().LogWarning($"An empty file \"{filename}\" in the \"{Path.Combine(path, filename)}\" directory was not created due to \"{e.Message}\"");
                return false;
            }
        }

19 Source : PdfImageConverter.cs
with MIT License
from allantargino

private FileInfo ToFile(Stream stream, string fileName)
        {
            string pdfFile = $@"{_tempFolder}\{fileName}";

            using (var fileStream = File.Create(pdfFile))
            {
                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(fileStream);
                stream.Close();
            }

            return new FileInfo(pdfFile);
        }

19 Source : ParquetConvert.cs
with MIT License
from aloneguid

public static Schema Serialize<T>(IEnumerable<T> objectInstances, string filePath,
         Schema schema = null,
         CompressionMethod compressionMethod = CompressionMethod.Snappy,
         int rowGroupSize = 5000,
         bool append = false)
         where T : new()
      {
         using (Stream destination = System.IO.File.Create(filePath))
         {
            return Serialize(objectInstances, destination, schema, compressionMethod, rowGroupSize, append);
         }
      }

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 : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static void ClearLog() {
			if(lastPath == null){lastPath = Application.persistentDataPath + "/" + Application.productName + "/Logs/SysLog.txt";}
			if(!Directory.Exists(System.IO.Path.GetDirectoryName(lastPath))){
				Directory.CreateDirectory(System.IO.Path.GetDirectoryName(lastPath));
				File.Create(lastPath).Dispose();
			} else {
				if(!File.Exists(lastPath)){
					File.Create(lastPath).Dispose();
				} else {
					File.WriteAllLines(lastPath, new string[]{""});
				}
			}
			logData.Clear();
			logRaw.Clear();
		}

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static void SaveDataToFile(string path, string[] data){
			if(!File.Exists(path)){
				File.Create(path).Dispose();
				foreach(string d in data){
					File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
				}
			} else {
				File.Create(path).Dispose();
				foreach(string d in data){
					File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
				}
			}
			
		}

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static void SaveFile(string path, string[] data, bool clearOldFiles){
			if(!File.Exists(path)){
				File.Create(path).Dispose();
				foreach(string d in data){
					File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
				}
			} else {
				if(clearOldFiles){
					File.Create(path).Dispose();
					foreach(string d in data){
						File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
					}
				} else {
					foreach(string d in data){
						File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
					}
				}
			}
			
		}

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static void SaveSystemInfo (string path) {
			if(!File.Exists(path)){
				File.Create(path).Dispose();
				temporaryPath = path;
			} else {
				temporaryPath = path;
			}
			i = 0;
				sysInfo.Add("--- SystemInfo --- ");
				sysInfo.Add("Battery Level: " + (SystemInfo.batteryLevel *100) + "%");
				sysInfo.Add("Battery Status: " + SystemInfo.batteryStatus.ToString());
				sysInfo.Add("Copy Texture Support: " + SystemInfo.copyTextureSupport.ToString());
				sysInfo.Add("Device Model: " + SystemInfo.deviceModel);
				sysInfo.Add("Device Name: " + SystemInfo.deviceName);
				sysInfo.Add("Device Type: " + SystemInfo.deviceType.ToString());
				sysInfo.Add("Unique Device ID: " + SystemInfo.deviceUniqueIdentifier);
				sysInfo.Add("Graphics Device ID: " + SystemInfo.graphicsDeviceID);
				sysInfo.Add("Graphics Device Name: " + SystemInfo.graphicsDeviceName);
				sysInfo.Add("Graphics Device Type: " + SystemInfo.graphicsDeviceType.ToString());
				sysInfo.Add("Graphics Device Vendor: " + SystemInfo.graphicsDeviceVendor);
				sysInfo.Add("Graphics Device VendorID: " + SystemInfo.graphicsDeviceVendorID);
				sysInfo.Add("Graphics Device Version: " + SystemInfo.graphicsDeviceVersion);
				sysInfo.Add("Graphics Memory Size: " + SystemInfo.graphicsMemorySize);//
				sysInfo.Add("Graphics Mulreplacedhreaded: " + SystemInfo.graphicsMulreplacedhreaded);
				sysInfo.Add("Graphics Shader Level: " + SystemInfo.graphicsShaderLevel);
				sysInfo.Add("Graphics UV Starts at Top?: " + SystemInfo.graphicsUVStartsAtTop);
				sysInfo.Add("Max Cubemap Size: " + SystemInfo.maxCubemapSize);
				sysInfo.Add("Max Texture Size: " + SystemInfo.maxTextureSize);
				sysInfo.Add("NPOT Support: " + SystemInfo.npotSupport.ToString());
				sysInfo.Add("OS: " + SystemInfo.operatingSystem);
				sysInfo.Add("OS Family: " + SystemInfo.operatingSystemFamily.ToString());
				sysInfo.Add("Processor Count: " + SystemInfo.processorCount);
				sysInfo.Add("Processor Frequency: " + SystemInfo.processorFrequency + "MHz");
				sysInfo.Add("Processor Type: " + SystemInfo.processorType);
				sysInfo.Add("Supported Render Targer Count: " + SystemInfo.supportedRenderTargetCount);
				if(SystemInfo.supports2DArrayTextures){sysInfo.Add("Supports 2D Array Textures : Yes");} else { sysInfo.Add("Supports 2D Array Textures : No");}
				if(SystemInfo.supports3DRenderTextures){sysInfo.Add("Supports 3D Render Textures : Yes");} else { sysInfo.Add("Supports 3D Render Textures : No");}
				if(SystemInfo.supports3DTextures){sysInfo.Add("Supports 3D Textures : Yes");} else { sysInfo.Add("Supports 3D Textures : No");}
				if(SystemInfo.supportsAccelerometer){sysInfo.Add("Supports Accelerometer : Yes");} else { sysInfo.Add("Supports Accelerometer : No");}
				if(SystemInfo.supportsAudio){sysInfo.Add("Supports Audio : Yes");} else { sysInfo.Add("Supports Audio : No");}
				if(SystemInfo.supportsComputeShaders){sysInfo.Add("Supports Compute Shaders : Yes");} else { sysInfo.Add("Supports Compute Shaders : No");}
				if(SystemInfo.supportsCubemapArrayTextures){sysInfo.Add("Supports Cubemap Array Textures : Yes");} else { sysInfo.Add("Supports Cubemap Array Textures : No");}
				if(SystemInfo.supportsGyroscope){sysInfo.Add("Supports Gyroscope : Yes");} else { sysInfo.Add("Supports Gyroscope : No");}
				if(SystemInfo.supportsImageEffects){sysInfo.Add("Supports Image Effects : Yes");} else { sysInfo.Add("Supports Image Effects : No");}
				if(SystemInfo.supportsInstancing){sysInfo.Add("Supports Instancing : Yes");} else { sysInfo.Add("Supports Instancing : No");}
				if(SystemInfo.supportsLocationService){sysInfo.Add("Supports Location Services : Yes");} else { sysInfo.Add("Supports Location Services : No");}
				if(SystemInfo.supportsMotionVectors){sysInfo.Add("Supports Motion Vectors : Yes");} else { sysInfo.Add("Supports Motion Vectors : No");}
				if(SystemInfo.supportsRawShadowDepthSampling){sysInfo.Add("Supports Raw Shadow Depth Sampling : Yes");} else { sysInfo.Add("Supports Raw Shadow Depth Sampling : No");}
				if(SystemInfo.supportsRenderToCubemap){sysInfo.Add("Supports Render To Cubemap : Yes");} else { sysInfo.Add("Supports Render To Cubemap : No");}
				if(SystemInfo.supportsShadows){sysInfo.Add("Supports Shadows : Yes");} else { sysInfo.Add("Supports Shadows : No");}
				if(SystemInfo.supportsSparseTextures){sysInfo.Add("Supports Sparse Textures : Yes");} else { sysInfo.Add("Supports Sparse Textures : No");}
				if(SystemInfo.supportsVibration){sysInfo.Add("Supports Vibration : Yes");} else { sysInfo.Add("Supports Vibration : No");}
				sysInfo.Add("System Memory Size: " + SystemInfo.systemMemorySize);
				sysInfo.Add("Unsupported Identifier: " + SystemInfo.unsupportedIdentifier);
				if(SystemInfo.usesReversedZBuffer){sysInfo.Add("Uses Reversed Z Buffer : Yes");} else { sysInfo.Add("Uses Reversed Z Buffer : No");}
				sysInfo.Add(string.Format("{0} {1}", "", System.Environment.NewLine));
				sysInfo.Add("--- " + System.DateTime.Now.ToString()+" ---" );
				WriteDataToFile(false);
		}

19 Source : Sys_API_CSharp_Example.cs
with GNU General Public License v3.0
from Alpaca-Studio

public void Awake () {
		#if UNITY_EDITOR
			dir = Application.persistentDataPath;
			//dir = Application.dataPath;
		#endif
		#if UNITY_ANDROID && !UNITY_EDITOR
			dir = "/storage/emulated/0";
			//dir = Application.persistentDataPath;
			//dir = Application.dataPath;
		#endif
		#if UNITY_IOS && !UNITY_EDITOR
			dir = Application.persistentDataPath;
			//dir = Application.dataPath;
		#endif
		dataPath = dir + "/" + Application.productName + "/Logs";
		if(!Directory.Exists(dataPath)){
			Directory.CreateDirectory(dataPath);
			File.Create(dataPath + "/" + logFileName).Dispose();
			dataPath = dir + "/"+ Application.productName + "/Logs";
		} else {
			if(!File.Exists(dataPath + "/" + logFileName)){
				File.Create(dataPath + "/" + logFileName).Dispose();
				dataPath = dir + "/"+ Application.productName + "/Logs";
			} else {
				dataPath = dir + "/"+ Application.productName + "/Logs";
			}
			
		}
	}

19 Source : SYS_MASTER.cs
with GNU General Public License v3.0
from Alpaca-Studio

public static void SaveFile(string path, string[] data){
			if(!File.Exists(path)){
				File.Create(path).Dispose();
				foreach(string d in data){
					File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
				}
			} else {
				File.Create(path).Dispose();
				foreach(string d in data){
					File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
				}
			}
			
		}

See More Examples