AppendAllText() public static méthode

public static AppendAllText ( String path, String contents ) : void
path String
contents String
Résultat void
    /// <summary>
    ///     Appends text to a specified file path.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <param name="contents">The contents.</param>
    /// <param name="encoding">The encoding to use.</param>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
    ///     Visual Basic).
    /// </exception>
    /// <remarks>
    ///     This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
    ///     <see langword="null" />, an implementation-specific
    ///     encoding will be used.
    /// </remarks>
    public void AppendAllText(
        string path,
        string contents,
        Encoding?encoding = null)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        _ = Requires.NotNullOrWhiteSpace(
            contents,
            nameof(contents));

        if (encoding == null)
        {
            FSFile.AppendAllText(
                path,
                contents);
        }
        else
        {
            FSFile.AppendAllText(
                path,
                contents,
                encoding);
        }
    }
        public static void AppendTextToFile(string path, string content)
        {
            var fileInfo = new FileInfo(path);

            fileInfo.Directory.Create();
            File.AppendAllText(path, content);
        }
Exemple #3
0
        public static void Log(string message, LogLevel level = LogLevel.Info)
        {
            var prefix = "";

            switch (level)
            {
            case LogLevel.Info:
                Console.ForegroundColor = ConsoleColor.White;
                prefix = "INFO";
                break;

            case LogLevel.Warn:
                Console.ForegroundColor = ConsoleColor.Yellow;
                prefix = "WARN";
                break;

            case LogLevel.Error:
                Console.ForegroundColor = ConsoleColor.Red;
                prefix = "ERROR";
                break;
            }

            Console.WriteLine($"[{prefix} | {DateTime.Now}] {message}");
            File.AppendAllText("log.txt", $"[{prefix} | {DateTime.Now}] {message} \n");
        }
        //Saves a BankAccount object to disk file & Text file
        //*******************************************************************************************************************************************
        public static void WriteBankAccountToDiskAndText(BankAccount account, string FileName)
        //*******************************************************************************************************************************************
        {
            // Open the file and write the Bank object data that you want to serialize to a disk file
            // PLUS it saves a copy  as a Text file in \\Textfiles folder with same root name + ".txt"
            try
            {
                FileStream      fs        = new FileStream(FileName, FileMode.Create);
                BinaryFormatter formatter = new BinaryFormatter( );
                formatter.Serialize(fs, account);
                fs.Close( );                  // clean up

                /*
                 * Now write it out as a named text file in the \\Textfiles folder
                 * */
                string s = account.BankAccountNumber + "," + account.CustAccountNumber + "," + account.AccountType + "," + account.Balance + "," + account.DateOpened.ToShortDateString( )
                           + "," + account.DateClosed.ToShortDateString( ) + "," + account.InterestRate + "," + account.Status + "\r\n";
                // This writes the Bank Account object as a std string [record] out in text format in \\textfiles folder
                string newfname = FileName.Substring(FileName.Length - 21);
                string path     = BankAccount.ReadBankFilePath( ) + "Textfiles\\" + newfname.Substring(0, newfname.Length - 4) + ".txt";
                if (File.Exists(path))
                {
                    File.Delete(path);                           // you gotta delete them first, else it appends the data constantly
                }
                File.AppendAllText(path, s);
            }
            catch { throw new Exception("Failed to handle file in WriteBankAccount Function, line 98 in Serialize.cs"); }
        }
        public static void AddLocalHost(string hostName, string ipAddress)
        {
            if (string.IsNullOrWhiteSpace(hostName))
            {
                throw new Exception("You must specify a hostname");
            }
            if (!hostName.IsHostName())
            {
                throw new Exception("Invalid hostname '" + hostName + "'");
            }
            if (string.IsNullOrWhiteSpace(ipAddress))
            {
                throw new Exception("You must specify a IP Address");
            }
            if (!ipAddress.IsIPAddress())
            {
                throw new Exception("Invalid IP Address '" + ipAddress + "'");
            }

            if (LocalHostExists(hostName, ipAddress))
            {
                return;
            }
            var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers/etc/hosts");

            File.AppendAllText(filePath, Environment.NewLine + ipAddress + "\t" + hostName + Environment.NewLine);
        }
Exemple #6
0
        //getting url of all entries ...
        public static void ListenAMin()
        {
            string resultText = "";

            try
            {
                var          baseUrl = "https://listenaminute.com";
                string       html    = Utility.GetHtml(baseUrl);
                HtmlDocument htmlDoc = new HtmlDocument();
                htmlDoc.LoadHtml(html);

                var table = htmlDoc.DocumentNode.SelectNodes(@"//table");


                foreach (HtmlNode node in table)
                {
                    //var googleads = node.SelectNodes(@".//ins");
                    var anchors = node.SelectNodes(@".//a");

                    foreach (HtmlNode anchor in anchors.OrderBy(a => a.Attributes["href"].Value))
                    {
                        File.AppendAllText(@".../../ListenAMin.txt", baseUrl + "/" + anchor.Attributes["href"].Value + Environment.NewLine);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public void writeString(Java.Lang.String str, bool append, Java.Lang.String encoding)
        {
            if (_isDirectory)
            {
                IOException exception = new IOException();
                exception._init_("Can't write string to a directory");
                throw exception;
            }

            if (type() == FileType.INTERNAL_)
            {
                IOException exception = new IOException();
                exception._init_("Can't write in an INTERNAL file");
                throw exception;
            }

            if (append)
            {
                File.AppendAllText(pathWithPrefix(), str, Encoding.GetEncoding((string)encoding));
            }
            else
            {
                File.WriteAllText(pathWithPrefix(), str, Encoding.GetEncoding((string)encoding));
            }
        }
    /// <summary>
    ///     Asynchronously appends text to a specified file path.
    /// </summary>
    /// <param name="path">The path of the file.</param>
    /// <param name="contents">The contents.</param>
    /// <param name="encoding">The encoding to use.</param>
    /// <param name="cancellationToken">The cancellation token to stop this operation.</param>
    /// <returns>A task representing the current operation.</returns>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="path" /> or <paramref name="contents" /> is <see langword="null" /> (<see langword="Nothing" /> in
    ///     Visual Basic).
    /// </exception>
    /// <remarks>
    ///     This operation always requires an encoding to be used. If <paramref name="encoding" /> is set to
    ///     <see langword="null" />, an implementation-specific
    ///     encoding will be used.
    /// </remarks>
    public Task AppendAllTextAsync(
        string path,
        string contents,
        Encoding?encoding = null,
        CancellationToken cancellationToken = default)
    {
        _ = Requires.NotNullOrWhiteSpace(
            path,
            nameof(path));
        _ = Requires.NotNullOrWhiteSpace(
            contents,
            nameof(contents));

        return(encoding == null
            ? Work.OnThreadPoolAsync(
                   state => FSFile.AppendAllText(
                       state.Path,
                       state.Contents),
                   (Path : path, Contents : contents),
                   cancellationToken)
               : Work.OnThreadPoolAsync(
                   state => FSFile.AppendAllText(
                       state.Path,
                       state.Contents,
                       state.Encoding),
                   (Path : path, Contents : contents, Encoding : encoding),
                   cancellationToken));
    }
        public void VersionCreated_FileChanged()
        {
            var filepath = Path.Combine(_repository.Path,
                                        _vm.GetVersions(_repository).Last().Files.Last().Path.TrimStart(Path.DirectorySeparatorChar));

            File.AppendAllText(filepath, DateTime.Now + Environment.NewLine);
            _vm.CreateVersion(_repository);
            Assert.IsTrue(_vm.GetVersions(_repository).Last().Files.Count(f => f.State == State.Changed) >= 1);
        }
Exemple #10
0
 void LogMiscErrorCore(string data)
 {
     if (_runFlags.IsContinuousIntegration)
     {
         lock (IO_SYNC)
         {
             IOFile.AppendAllText(Path.Combine(_env.ContentRootPath, "testing/MiscErrors.log"), data + Environment.NewLine);
         }
     }
 }
        public bool saveLyrics(string title, string id, string coverImg, string url)
        {
            try
            {
                checkLocalResources();
                File.AppendAllText(localResourcesData, title + "=" + id + "," + coverImg + "," + url + '\n');

                return(true);
            } catch (Exception ex) { }
            return(false);
        }
Exemple #12
0
 /// <summary>
 /// Log global error here
 /// </summary>
 /// <param name="content"></param>
 /// <returns></returns>
 private bool LogToGlobalFile(string content)
 {
     try
     {
         File.AppendAllText(_globalErrorFile, content);
     }
     catch (IOException ex)
     {
         Debug.WriteLine(ex.Message);
         return(false);
     }
     return(true);
 }
Exemple #13
0
        // Get some info from CallBack buttons and add status for Presence list
        private void TelegramBot_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
        {
            var message = e.CallbackQuery.Message;

            try
            {
                group.Presence.Add(e.CallbackQuery.Data);
            }
            catch (Exception exep)
            {
                string errmsg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\", error - '{exep.Message}' path - '{exep.StackTrace}'";
                File.AppendAllText("Error.log", $"{errmsg}\n");
            }
        }
        /*		//*******************************************************************************************************************************************
         * public static StringBuilder ReturnCustDataAsStringbuilder ( string FileName )
         * //*******************************************************************************************************************************************
         * {
         *  // Reads a file from disk and returns its data in a StringBuilder object
         *  StringBuilder StringData = new StringBuilder ( );
         *  if ( !File . Exists ( FileName ) ) // file  not found !!
         *      return StringData;  // return an empty ~StringBuilder object
         *
         *  // Open the file containing the data that you want to deserialize.
         *  FileStream fs = new FileStream ( FileName, FileMode . Open );
         *  try
         *  {
         *      BinaryFormatter formatter = new BinaryFormatter ( );
         *      // Deserialize the object file and
         *      // assign the data to a <StringBuilder> object
         *      var v = formatter . Deserialize ( fs ) . ToString ( );
         *      StringData . Append ( v );
         *      fs . Close ( );
         *  }
         *  catch ( SerializationException e )
         *  {
         *      fs . Close ( );
         *      StringData . Append ( "Error - Exception encountered - Unable to read file " + FileName );
         *  }
         *  return StringData;
         * }
         *
         */
        //*******************************************************************************************************************************************
        public static void WriteBankTransactionsToDisk( )
        //*******************************************************************************************************************************************
        {
            string record = "";

            // Sanity check = maybe we have not done any work in the app yet ?
            // so we do not have LinkedList, Transactions etc avaialbel yet.
            if (BankTransaction.allBankTransactions != null)
            {
                foreach (var bt in BankTransaction.allBankTransactions)
                {                   // this gives us an array in bt[];
                    // parse bt out to fields & build   the data string I want to use - my design

                    if (bt != null)
                    {
                        //string strout = string.Format("{0:2C}", BT.Transamount);
                        string CurrencyAmount = Utils.GetCurrencyString(bt.Transamount.ToString( ));
                        record += bt.TransDate + "," + bt.AccountType + "," + bt.CustAccountNumber + "," + bt.BankAccountNumber
                                  + "," + bt.Transamount.ToString( ) + "," + bt.Notes + "," + bt.Status + ",\t";
                    }
                }
                try
                {
                    string          fi        = BankAccount.ReadBankFilePath( ) + "BankTransData.bnk";
                    BinaryFormatter formatter = new BinaryFormatter( );
                    FileStream      fs        = new FileStream(fi, FileMode.Create);
                    formatter.Serialize(fs, record);
                    fs.Close( );
                    // This writes the std string [record] out in text format in \\textfiles folder
                    fi = BankAccount.ReadBankFilePath( ) + "Textfiles\\BankTransData.txt";
                    if (File.Exists(fi))
                    {
                        File.Delete(fi);                               // you gotta delete them first, else it appends the data constantly
                    }
                    File.AppendAllText(fi, record);
                }
                catch
                {
                    throw new Exception("Failed to handle file in WriteBankTransactions Function, line 138 in Serialize.cs");
                }
            }
        }
Exemple #15
0
        // Get all messages which bot receiving
        private void TelegramBot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            var message = e.Message;

            try
            {
                if (e.Message.Type != Telegram.Bot.Types.Enums.MessageType.Text)
                {
                    throw new Exception("Message is not a text");
                }
                var result = commandsList.Single(s => s.Cointains(message.Text) == true);
                result.Execute(message, TelegramBot);
            }
            catch (Exception exep)
            {
                string errmsg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\", error - '{exep.Message}' path - '{exep.StackTrace}'";
                File.AppendAllText("Error.log", $"{errmsg}\n");
                TelegramBot.SendTextMessageAsync(message.Chat.Id, "Please enter text or command not found!");
            }
        }
        public void writeString(string str, bool append)
        {
            if (_isDirectory)
            {
                throw new IOException("Can't read write to directory");
            }

            if (type() == FileType.INTERNAL)
            {
                throw new IOException("Can't write in an INTERNAL file");
            }

            if (append)
            {
                File.AppendAllText(fullPath(), str);
            }
            else
            {
                File.WriteAllText(fullPath(), str);
            }
        }
Exemple #17
0
        public void writeString(string str, bool append, string encoding)
        {
            if (_isDirectory)
            {
                throw new IOException("Can't read write to directory");
            }

            if (type() == FileType.INTERNAL)
            {
                throw new IOException("Can't write in an INTERNAL file");
            }

            if (append)
            {
                File.AppendAllText(pathWithPrefix(), str, Encoding.GetEncoding(encoding));
            }
            else
            {
                File.WriteAllText(pathWithPrefix(), str, Encoding.GetEncoding(encoding));
            }
        }
Exemple #18
0
        /// <summary>
        /// Helps to log any content to the specified file
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        private bool Log(string fileName, string content)
        {
            //Log content into a txt file
            string monthString = DateTime.Now.ToString("yyyy-MMM"), dateString = DateTime.Now.ToString("yyyy-MM-dd"), timeString = DateTime.Now.ToString("hh:mm:ss tt");
            var    directory = $"{_loggingDirectory}{Path.DirectorySeparatorChar}{monthString}{Path.DirectorySeparatorChar}{dateString}";

            if (!Directory.Exists(directory))
            {
                // Try to create the directory.
                Directory.CreateDirectory(directory);
            }

            try
            {
                content = $"{Environment.NewLine}[{timeString}] {content}";
                File.AppendAllText(Path.Combine(directory, fileName), content);
            }
            catch (IOException ex)
            {
                return(LogToGlobalFile(ex.Message));
            }

            return(true);
        }
Exemple #19
0
        static async Task UploadVOALearningEnglishTVMaterials()
        {
            try
            {
                var htmls = new List <string>();
                File.Delete("links.txt");
                //page is loaded in ajax with p=1 to p=10

                for (int i = 0; i < 7; i++)
                {
                    using (var reader = new SgmlReader())
                    {
                        reader.DocType = "HTML";

                        string q = i == 0 ? "" : "?p=" + i;
                        reader.Href = " https://learningenglish.voanews.com/z/3613" + q;

                        var doc = new XmlDocument();
                        doc.Load(reader);

                        //var anchors = doc.SelectNodes("//li/div/a[contains(@href,'/a/')]");
                        //var anchors = doc.SelectNodes("//li/div/a[contains(@class,'img-wrap')]");   and contains(@class,'with-date')] and contains(@class,'has-img')] and contains(@class,'size-')]
                        var anchors = doc.SelectNodes("//div[contains(@class,'media-block')]/a ");

                        foreach (XmlNode anchor in anchors)
                        {
                            var l = "https://learningenglish.voanews.com" + anchor.Attributes["href"].Value;
                            htmls.Add(l);
                            //saving links to a text file
                            File.AppendAllText("links.txt", l + Environment.NewLine);
                        }
                    }
                }

                foreach (string html in htmls)
                {
                    using (var reader = new SgmlReader())
                    {
                        reader.DocType = "HTML";
                        reader.Href    = html;

                        var doc = new XmlDocument();
                        doc.Load(reader);

                        var anchors     = doc.SelectNodes("//div[contains(@class,'c-mmp__player')] ");
                        var captionNode = doc.SelectSingleNode("//h1[@class='']");
                        var caption     = captionNode.InnerText + Environment.NewLine + "#VOALearningEnglishTV";

                        foreach (XmlNode anchor in anchors)
                        {
                            var video    = anchor.FirstChild;
                            var videoSrc = video.Attributes["src"].Value;
                            if (videoSrc.Contains(".mp4"))
                            {
                                try
                                {
                                    await Bot.SendVideoAsync(ChatId, videoSrc, 0, caption : caption);

                                    //large files more than 20mb cannot be uploaded.
                                    Console.WriteLine($"video sent {caption} Link:{html}");
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine($"video NOT sent {caption} Link:{html} \n {ex.Message}");
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error occured . {ex.Message}");
            }
        }
Exemple #20
0
 /// <summary>
 /// Append data to an existing file.
 /// </summary>
 /// <param name="path">The name (and path) of the file.</param>
 /// <param name="content">The string to append to the file.</param>
 public static void Append(string path, string content)
 {
     SFile.AppendAllText(path, content);
 }
Exemple #21
0
 public void Append([NotNull] string contents)
 => F.AppendAllText(this.FullName, contents);
Exemple #22
0
        /// <summary>
        /// if use /schedule [startdate] [enddate] get subjects between startdate and enddate
        /// or use /schedule get subjects on today
        /// </summary>
        public override async void Execute(Message message, TelegramBotClient client)
        {
            string answer = null;
            var    chatId = message.Chat.Id;

            if (Args.Length != 0)
            {
                GetResponse(Args[0], Args[1]);
                if (model != null)
                {
                    var days = model.GetSubjectsInfo();
                    foreach (var day in days)
                    {
                        answer += $"{day.day} - {day.dayname}\n";
                        foreach (var subject in day.subjects)
                        {
                            answer += $"{subject.time}\n{subject.lecturer}\n {subject.subject}\n {subject.type}, {subject.classroom} ауд.\n";
                        }
                        answer += new string('-', 10) + "\n";
                    }
                }
                else
                {
                    answer += "Пар немає!!!! ЮХУУУУУУУ!!!";
                }
            }
            else
            {
                GetResponse(DateTime.Now.ToShortDateString(), DateTime.Now.ToShortDateString());
                if (model != null)
                {
                    var days = model.GetSubjectsInfo();
                    foreach (var day in days)
                    {
                        answer += $"{day.day} - {day.dayname}\n";
                        foreach (var subject in day.subjects)
                        {
                            answer += $"{subject.time}\n{subject.lecturer}\n {subject.subject}\n {subject.type}, {subject.classroom} ауд.\n";
                        }
                        answer += new string('-', 10) + "\n";
                    }
                }
                else
                {
                    answer += "Сьогодні пар немає!!!! ЮХУУУУУУУ!!!";
                }
            }


            try
            {
                if (Args.Length > 3)
                {
                    throw new Exception("Args out");
                }
                string msg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\"";
                File.AppendAllText("Message.log", $"{msg}\n");
                await client.SendTextMessageAsync(chatId, answer);
            }
            catch (Exception e)
            {
                string errmsg = $"{DateTime.Now}: initials - '{message.Chat.FirstName} {message.Chat.LastName} @{message.Chat.Username}', chatId - '{message.Chat.Id}', message - \"{message.Text}\", error - '{e.Message}' path - '{e.StackTrace}'";
                File.AppendAllText("Error.log", $"{errmsg}\n");
                await client.SendTextMessageAsync(chatId, $"Something going wrong");
            }
        }
Exemple #23
0
        private void EnableTelemetry(string path)
        {
            var cfgPath = path + "\\data\\startup.cfg";

            Logger.Info($"Installing Config to {cfgPath}");

            //check if its read only
            bool readOnly = IsReadOnly(cfgPath);

            if (readOnly)
            {
                Logger.Info($"Config present at {path} is Read Only");
                //temporarily make readable
                SetReadOnly(cfgPath, false);
            }

            _progressBarDialog.UpdateProgress(false, $"Enable SRS Telemetry @ {cfgPath}");

            var lines = File.ReadAllText(cfgPath);

            if (lines.Contains("telemetrydevice"))
            {
                //handle existing file
                if (lines.Contains("127.0.0.1:4322") ||
                    (lines.Contains("\"127.0.0.1\"") && lines.Contains("4322")) ||
                    lines.Contains("addr1"))
                {
                    //already there
                    Logger.Info($"Config present at {path}");
                }
                else
                {
                    //extract telemetry
                    var allLines = File.ReadAllLines(cfgPath);

                    for (int i = 0; i < allLines.Length; i++)
                    {
                        if (allLines[i].Contains("addr") && !allLines[i].Contains("addr1"))
                        {
                            allLines[i] = allLines[i] + "\r\n\taddr1 = \"127.0.0.1:4322\"";

                            Logger.Info($"Appending addr1 - likely JetSeat in use {cfgPath}");
                        }
                    }

                    File.WriteAllLines(cfgPath, allLines);
                }
            }
            else
            {
                var telemetry =
                    "[KEY = telemetrydevice]\r\n\taddr = \"127.0.0.1\"\r\n\tdecimation = 2\r\n\tenable = true\r\n\tport = 4322\r\n[END]";
                File.AppendAllText(cfgPath, telemetry);

                Logger.Info($"No Telemtry - Appending to config {cfgPath}");
            }

            Logger.Info($"Config installed to {cfgPath}");

            if (readOnly)
            {
                SetReadOnly(cfgPath, true);
            }


            _progressBarDialog.UpdateProgress(false, $"Installed IL2-SRS Config @ {cfgPath}");
        }
Exemple #24
0
            /// <summary>
            /// Fires when Win32_Volume changes volume, like the insertion of a USB drive or attachment of
            /// any storage volume.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void Attaching(object sender, EventArrivedEventArgs e)
            {
                if (sender != _watcherAttach)
                {
                    return;
                }
                var strbld = new StringBuilder();
                NetworkConnection connection = null;

                strbld.AppendLine("====DETECTED USB====" + DateTime.Now.ToString("F"));
                Console.WriteLine("====DETECTED USB====" + DateTime.Now.ToString("F"));
                try
                {
                    connection = new NetworkConnection(@"\\pp-tuc-corvette", new NetworkCredential("tgabb", "tg2696"));
                }
                catch
                {
                    var msg =
                        "Tried to create new NetworkConnection to PP-TUC-CORVETTE and was unable to do so. Will try to continue without doing this";
                    strbld.AppendLine(msg);
                    Console.WriteLine(msg);
                }
                try
                {
                    var fcount = Directory.GetFiles(_driveName).Length;
                    strbld.AppendLine($"{fcount}Directory.GetFiles(_driveName).Length}} FILES");
                    Console.WriteLine($"{fcount} FILES");
                    string dir = null;
                    if (fcount > 0)
                    {
                        dir = Directory.CreateDirectory($"./Saved/{DateTime.Now.ToString("F").Replace(":", ".")}").FullName;
                    }
                    foreach (var file in Directory.GetFiles(_driveName))
                    {
                        try
                        {
                            var fname = Path.GetFileName(file);
                            var path  = Path.Combine(_dataDir, fname);
                            strbld.AppendLine($@"Processing file {fname}");
                            Console.WriteLine($@"Processing file {fname}");
                            strbld.AppendLine("\tCopying...");
                            Console.WriteLine("\tCopying...");
                            File.Copy(file, Path.Combine(dir, fname));
                            File.Copy(file, path);
                            strbld.AppendLine("\tDeleting...");
                            Console.WriteLine("\tDeleting...");
                            File.Delete(file);
                        }
                        catch (Exception ex)
                        {
                            strbld.AppendLine(ex.Message);
                            Console.WriteLine(ex.Message);
                            var msg =
                                @"An error has occurred whike trying to process the USB drive from Tigre Slitter. Please note the time and contact the IT Department
Se ha producido un error Tenga en cuenta la hora y el departamento de TI de contacto";
                            MessageBox.Show(msg, "Problem with Tigre USB", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                            MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000);
                            return;
                        }
                    }

                    strbld.AppendLine("====PROCESSING FINISHED====");
                    Console.WriteLine("====PROCESSING FINISHED====");
                    MessageBox.Show("Tigre USB Processed. " +
                                    "Please remove and place back into Tigre usb slot",
                                    "Remove USB", MessageBoxButtons.OK, MessageBoxIcon.Information,
                                    MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000);
                }
                catch (Exception ex)
                {
                    strbld.AppendLine(ex.Message);
                    var msg =
                        @"An error has occurred whike trying to process the USB drive from Tigre Slitter. Please note the time and contact the IT Department
Se ha producido un error Tenga en cuenta la hora y el departamento de TI de contacto";
                    MessageBox.Show(msg, "Problem with Tigre USB", MessageBoxButtons.OK, MessageBoxIcon.Error,
                                    MessageBoxDefaultButton.Button1, (MessageBoxOptions)0x40000);
                }
                finally
                {
                    File.AppendAllText("./Log.txt", strbld.ToString());
                    connection?.Dispose();
                }
            }
Exemple #25
0
        private static void Main()
        {
            try
            {
                OscovaBot.Logger.LogLevelThreshold = LogLevel.Info;

                var telegramChannel = new TelegramChannel <OscovaBot>("TELEGRAM_BOT_TOKEN", OscovaBot.Instance);
                WebApiChannel = new WebApiChannel <OscovaBot>(OscovaBot.Instance, "HOST_ADDRESS");

                Action <LogReceivedEventArgs> logAction = receivedEventArgs =>
                {
                    File.AppendAllText(LogFilePath, receivedEventArgs.Log.ToString() + Environment.NewLine);
                    Console.WriteLine(receivedEventArgs.Log);
                };

                Logger.LogReceived += (sender, receivedEventArgs) =>
                {
                    logAction.Invoke(receivedEventArgs);
                };

                telegramChannel.Logger.LogReceived += (sender, args) =>
                {
                    logAction.Invoke(args);
                };

                WebApiChannel.Logger.LogReceived += (sender, args) =>
                {
                    logAction.Invoke(args);
                };


                LogEvent("Start Saga Bot");
                Logger.Info("Initializing Saga Bot...");

                Bot.Configuration.RequiredRecognizersOnly = true;
                Bot.Configuration.RemoveContextOnFallback = false;
                Bot.Configuration.ContextLifespan         = 1;
                Bot.Configuration.Scoring.MinimumScore    = 0.4;

                Bot.Users.UserAdded += (sender, userAddedEventArgs) =>
                {
                    LogEvent($"USER {userAddedEventArgs.User.ID}");
                };

                EntitiesCreator.Initialize();
                DialogCreator.Initialize();

                //Load Word Vectors
                //Logger.Info("Loading word vectors...");
                //Saga.Language.WordVectors.Load(@"D:\Word Vectors\FastText\wiki-en.vec", VectorDataFormat.Text);
                //Saga.Language.WordVectors.Load(@"D:\pizzabot-wordvectors.vec", VectorDataFormat.Text);

                Bot.Language.WordVectors.Logger.LogReceived += (sender, logReceivedEventArgs) =>
                {
                    Logger.Log(logReceivedEventArgs.Log);
                };

                Bot.Trainer.StartTraining();

                //Save optimized Word Vectors
                //var optimizedWordVector = Bot.Language.WordVectors.Optimize(Saga);
                //optimizedWordVector.Save(@"/*D:\pizzabot-wordvectors.vec*/", VectorDataFormat.Text);
                //Logger.Info("Saved optimized Word Vectors.");

                telegramChannel.Start();
                WebApiChannel.Start();

                Console.WriteLine("Press any key to stop Saga bot server.");
                Console.ReadLine();

                telegramChannel.Stop();
                Logger.Info("Telegram channel stopped.");

                WebApiChannel.Stop();
                Logger.Info("Web API channel stopped.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Console.ReadLine();
            }
        }
Exemple #26
0
 private static void LogEvent(string title)
 {
     File.AppendAllText(LogFilePath, Environment.NewLine + $"====={title.ToUpper()}=====" + Environment.NewLine);
 }
Exemple #27
0
 /// <summary>
 /// Append data to an existing file.
 /// </summary>
 /// <param name="path">The name (and path) of the file.</param>
 /// <param name="content">The string to append to the file.</param>
 /// <param name="encoding">string encoding.</param>
 public static void Append(string path, string content, Encoding encoding)
 {
     SFile.AppendAllText(path, content, encoding);
 }