AppendText() public static méthode

public static AppendText ( String path ) : StreamWriter
path String
Résultat StreamWriter
Exemple #1
0
 public void ItemDClick(object sender, MouseEventArgs e)
 {
     if (e.Button == MouseButtons.Right)
     {
         FlowPanel.Controls.Remove((PictureBox)sender);
         Con.TryGetValue((PictureBox)sender, out string file);
         File.Delete(file);
         return;
     }
     if (e.Clicks > 1)
     {
         try
         {
             Con.TryGetValue((PictureBox)sender, out string file);
             Process          prc = new Process();
             ProcessStartInfo psi = new ProcessStartInfo(file);
             if (file.EndsWith(".lnk", StringComparison.OrdinalIgnoreCase))
             {
                 psi = new ProcessStartInfo(GetTargetPath(file));
                 psi.WorkingDirectory = GetWorkingDirectory(file);
                 psi.Arguments        = GetArgument(file);
             }
             if (psi.FileName.EndsWith(".exe") || psi.FileName.EndsWith(".msi"))
             {
                 if (UACChecker.RequiresElevation(psi.FileName))
                 {
                     psi.Verb = "runas";
                 }
             }
             if (psi.FileName == "")
             {
                 psi.FileName = file;
             }
             psi.UseShellExecute        = true;
             psi.RedirectStandardOutput = false;
             psi.RedirectStandardInput  = false;
             psi.CreateNoWindow         = false;
             prc.StartInfo = psi;
             prc.Start();
             Application.Exit();
         } catch (Exception ex)
         {
             using (StreamWriter sw = File.AppendText(Environment.CurrentDirectory + @"\log.txt"))
             {
                 sw.WriteLine("[Error] Execution error with folder {0}!", L_Title.Text);
                 foreach (string line in ex.Message.Split('\n'))
                 {
                     sw.WriteLine("[Error] {0}", line);
                 }
             }
             DialogResult dr = MessageBox.Show(ex.Message, "Execution Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
             if (dr == DialogResult.OK)
             {
                 Environment.Exit(1);
             }
             Thread.Sleep(2000);
         }
     }
 }
    /// <summary>
    ///     Opens a <see cref="StreamWriter" /> to append text to a file.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <returns>
    ///     A <see cref="StreamWriter" /> that can write to a file.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> is <see langword="null" /> (<see langword="Nothing" /> in Visual Basic).
    /// </exception>
    public StreamWriter AppendText(string path)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));

        return(FSFile.AppendText(path));
    }
 public void LogWarning(string message, params object[] args)
 {
     Console.WriteLine(string.Concat("WARN: ", message), args);
     using (StreamWriter logfile = File.AppendText("log.xml"))
     {
         logfile.WriteLine("<log><message>" + message + "</message></log> ", args);
     }
 }
Exemple #4
0
 static void lastDitchErrorLog(string file, Exception e)
 {
     // bug if this fails we are truly skrood
     try {
         using (var appender = File.AppendText(file + ".error"))
             appender.WriteLine(DateTime.Now + errMessage("failed makeOld on " + file + "\r\n", e));
     } catch {
         consoleOut("god i wish this message was visible from rightedge.");
     }
 }
Exemple #5
0
            public SkryptObject Append(SkryptEngine engine, SkryptObject self, SkryptObject[] values)
            {
                var s   = (File)self;
                var str = TypeConverter.ToString(values, 0, engine);

                using (StreamWriter sw = SysFile.AppendText(s.Path)) {
                    sw.Write(str);
                }

                return(self);
            }
Exemple #6
0
        private static void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Text == "/start" || message.Chat.Id == QaBillingChatId)
            {
                return;
            }
            if (message.Text == "/ping")
            {
                Bot.SendTextMessageAsync(message.Chat.Id, GetRandomPingResponse());
                return;
            }

            var gif = new FileToSend(GetRandomGifUri());

            var chatId            = QaBillingChatId;
            var cancellationToken = new CancellationTokenSource(3000).Token;
            var successSend       = false;

            try
            {
                Bot.ForwardMessageAsync(chatId, message.Chat.Id, message.MessageId, cancellationToken: cancellationToken)
                .GetAwaiter()
                .GetResult();
                successSend = true;
                Bot.SendVideoAsync(chatId, gif, cancellationToken: cancellationToken).GetAwaiter().GetResult();
            }
            catch (Exception)
            {
                using (StreamWriter w = File.AppendText("log.txt"))
                {
                    Log(message, w);
                }
            }

            if (successSend)
            {
                Bot.SendTextMessageAsync(message.Chat.Id,
                                         @"Дорогой друг! Твое сообщение передано группе тестирования Биллинга, скоро с тобой свяжутся и ответят.",
                                         cancellationToken: cancellationToken).GetAwaiter().GetResult();
            }
            else
            {
                Bot.SendTextMessageAsync(message.Chat.Id,
                                         @"Дорогой друг! К сожалению, возникли сложности с пересылкой сообщения, попробуй написать кому-нибудь из тестировщиков Биллинга в личку",
                                         cancellationToken: cancellationToken).GetAwaiter().GetResult();
            }
            Bot.SendVideoAsync(message.Chat.Id, gif, cancellationToken: cancellationToken).GetAwaiter().GetResult();
        }
Exemple #7
0
        private static void Main()
        {
            var sw = default(StreamWriter);

            try
            {
                var fileDir = new DirectoryInfo(ConfigurationManager.AppSettings["DirLocation"] + @"\Log\");
                if (!fileDir.Exists)
                {
                    fileDir.Create();
                }

                sw = File.Exists(fileDir.FullName + "TrackLog.txt")
                    ? File.AppendText(fileDir.FullName + "TrackLog.txt")
                    : File.CreateText(fileDir.FullName + "TrackLog.txt");
                sw.WriteLine("======================= Schedular Started, Dated : " + DateTime.Now + " ==========================");

                ReadDownloadedFile(sw);
            }
            catch (Exception ex)
            {
                if (sw != null)
                {
                    sw.WriteLine("Main - " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    sw.WriteLine(ex.InnerException?.Message ?? ex.Message + " - " + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                }
            }
            finally
            {
                if (sw != null)
                {
                    sw.WriteLine("======================= SchedularEnded, Dated : " + DateTime.Now + " ==========================");
                    sw.Close();
                    sw.Dispose();
                }
            }
        }
        private void InstallScripts(string path)
        {
            Logger.Info($"Installing Scripts to {path}");
            _progressBarDialog.UpdateProgress(false, $"Creating Script folders @ {path}");
            //Scripts Path
            CreateDirectory(path + "\\Scripts");
            CreateDirectory(path + "\\Scripts\\Hooks");

            //Make Tech Path
            CreateDirectory(path + "\\Mods");
            CreateDirectory(path + "\\Mods\\Tech");
            CreateDirectory(path + "\\Mods\\Tech\\DCS-SRS");

            Task.Delay(TimeSpan.FromMilliseconds(100)).Wait();

            _progressBarDialog.UpdateProgress(false, $"Updating / Creating Export.lua @ {path}");
            Logger.Info($"Handling Export.lua");
            //does it contain an export.lua?
            if (File.Exists(path + "\\Scripts\\Export.lua"))
            {
                var contents = File.ReadAllText(path + "\\Scripts\\Export.lua");

                contents.Split('\n');

                if (contents.Contains("SimpleRadioStandalone.lua") && !contents.Contains("Mods\\Tech\\DCS-SRS\\Scripts\\DCS-SimpleRadioStandalone.lua"))
                {
                    Logger.Info($"Updating existing Export.lua with existing SRS install");
                    var lines = contents.Split('\n');

                    StringBuilder sb = new StringBuilder();

                    foreach (var line in lines)
                    {
                        if (line.Contains("SimpleRadioStandalone.lua"))
                        {
                            sb.Append("\n");
                            sb.Append(EXPORT_SRS_LUA);
                            sb.Append("\n");
                        }
                        else if (line.Trim().Length > 0)
                        {
                            sb.Append(line);
                            sb.Append("\n");
                        }
                    }
                    File.WriteAllText(path + "\\Scripts\\Export.lua", sb.ToString());
                }
                else
                {
                    Logger.Info($"Appending to existing Export.lua");
                    var writer = File.AppendText(path + "\\Scripts\\Export.lua");

                    writer.WriteLine("\n" + EXPORT_SRS_LUA + "\n");
                    writer.Close();
                }
            }
            else
            {
                Logger.Info($"Creating new Export.lua");
                var writer = File.CreateText(path + "\\Scripts\\Export.lua");

                writer.WriteLine("\n" + EXPORT_SRS_LUA + "\n");
                writer.Close();
            }


            //Now sort out Scripts//Hooks folder contents
            Logger.Info($"Creating / installing Hooks & Mods");
            _progressBarDialog.UpdateProgress(false, $"Creating / installing Hooks & Mods @ {path}");
            try
            {
                File.Copy(_currentDirectory + "\\Scripts\\Hooks\\DCS-SRS-hook.lua", path + "\\Scripts\\Hooks\\DCS-SRS-hook.lua",
                          true);
                DirectoryCopy(_currentDirectory + "\\Scripts\\DCS-SRS", path + "\\Mods\\Tech\\DCS-SRS");
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(
                    "Install files not found - Unable to install! \n\nMake sure you extract all the files in the zip then run the Installer",
                    "Not Unzipped", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }
            Logger.Info($"Scripts installed to {path}");

            _progressBarDialog.UpdateProgress(false, $"Installed Hooks & Mods @ {path}");
        }
Exemple #9
0
        private void InstallScripts(string path)
        {
            //if scripts folder doesnt exist, create it
            Directory.CreateDirectory(path);
            Directory.CreateDirectory(path + "\\Hooks");
            Thread.Sleep(100);

            var write = true;

            //does it contain an export.lua?
            if (File.Exists(path + "\\Export.lua"))
            {
                var contents = File.ReadAllText(path + "\\Export.lua");

                if (contents.Contains("SimpleRadioStandalone.lua"))
                {
//                    contents =
//                        contents.Replace(
//                            "local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])",
//                            "local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])");
//                    contents = contents.Trim();
//
//                    File.WriteAllText(path + "\\Export.lua", contents);

                    // do nothing
                }
                else
                {
                    var writer = File.AppendText(path + "\\Export.lua");

                    writer.WriteLine(
                        "\n  local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])\n");
                    writer.Close();
                }
            }
            else
            {
                var writer = File.CreateText(path + "\\Export.lua");

                writer.WriteLine(
                    "\n  local dcsSr=require('lfs');dofile(dcsSr.writedir()..[[Scripts\\DCS-SimpleRadioStandalone.lua]])\n");
                writer.Close();
            }

            try
            {
                File.Copy(currentDirectory + "\\DCS-SimpleRadioStandalone.lua",
                          path + "\\DCS-SimpleRadioStandalone.lua", true);

                File.Copy(currentDirectory + "\\DCS-SRSGameGUI.lua",
                          path + "\\DCS-SRSGameGUI.lua", true);

                File.Copy(currentDirectory + "\\DCS-SRS-OverlayGameGUI.lua", path + "\\DCS-SRS-OverlayGameGUI.lua",
                          true);

                File.Copy(currentDirectory + "\\DCS-SRS-Overlay.dlg", path + "\\DCS-SRS-Overlay.dlg",
                          true);

                File.Copy(currentDirectory + "\\DCS-SRS-hook.lua", path + "\\Hooks\\DCS-SRS-hook.lua",
                          true);
            }
            catch (FileNotFoundException ex)
            {
                MessageBox.Show(
                    "Install files not found - Unable to install! \n\nMake sure you extract all the files in the zip then run the Installer",
                    "Not Unzipped", MessageBoxButton.OK, MessageBoxImage.Error);
                Environment.Exit(0);
            }
        }
Exemple #10
0
        public async static Task LetturaScritturaFileAsync2()
        {
            //piu step:
            //creo cartella + sottocarte con file


            DirectoryInfo directory = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "ProvaLetturascrittura"));

            try
            {
                //creazione cartelle
                directory.Create();
                Console.WriteLine(" cartella creata");
                directory.CreateSubdirectory("ProvaScrittura");
                Console.WriteLine("Subdirectory creata correttamente");

                //creazionefile
                string path = Path.Combine(directory.FullName, "ProvaScrittura/SequenzaNumeri.txt"); //parti da directory
                using (StreamWriter file = File.CreateText(path))                                    //uso stramwriter per scrivere nel file
                {
                    for (int i = 0; i <= 10; i++)
                    {
                        await file.WriteAsync(i.ToString() + "\n");// conversione in stringa
                    }
                }
                using (StreamWriter file = File.AppendText(path))// se avessi lascito create avrebbe sovrascritto, in questo modo aggiungo
                {
                    for (int i = 10; i <= 20; i++)
                    {
                        await file.WriteAsync(i.ToString() + "\n");// conversione in stringa
                    }
                }

                // letturafile
                string line;
                int    counter = 0; //mi dice a che riga sono

                using (StreamReader fileReader = File.OpenText(path))
                {
                    while ((line = fileReader.ReadLine()) != null) // mostro a schermo la riga
                    {
                        Console.WriteLine(line);
                        counter++;
                    }
                    line = ""; //resetto la riga
                    fileReader.BaseStream.Position = 0;

                    //lettura totale del test
                    line = fileReader.ReadToEnd();
                    Console.WriteLine(line);  // mi mette tutto in una riga


                    //split
                    string[] linesplit = line.Split("\n"); //divide in base ad una separatore

                    foreach (string el in linesplit)
                    {
                        Console.Write(el + " ");
                    }
                }
            }
            catch (Exception e)
            { Console.WriteLine(e.Message); }
        }