C# (CSharp) Класс System.IO. StreamWriter Code Examples

C# (CSharp) System.IO.StreamWriter - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для класса System.IO.StreamWriter, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Наследование: TextWriter
Пример #1
0
 public static void SavePointsInFile(string fileName, Path3D path)
 {
     using (StreamWriter file = new StreamWriter(fileName))
     {
         file.Write(path);
     }
 }
        public void AllFieldsEmptyTest()
        {
            using( var stream = new MemoryStream() )
            using( var reader = new StreamReader( stream ) )
            using( var writer = new StreamWriter( stream ) )
            using( var parser = new CsvParser( reader ) )
            {
                writer.WriteLine( ";;;;" );
                writer.WriteLine( ";;;;" );
                writer.Flush();
                stream.Position = 0;

                parser.Configuration.Delimiter = ";;";
                parser.Configuration.HasHeaderRecord = false;

                var row = parser.Read();
                Assert.IsNotNull( row );
                Assert.AreEqual( 3, row.Length );
                Assert.AreEqual( "", row[0] );
                Assert.AreEqual( "", row[1] );
                Assert.AreEqual( "", row[2] );

                row = parser.Read();
                Assert.IsNotNull( row );
                Assert.AreEqual( 3, row.Length );
                Assert.AreEqual( "", row[0] );
                Assert.AreEqual( "", row[1] );
                Assert.AreEqual( "", row[2] );

                row = parser.Read();
                Assert.IsNull( row );
            }
        }
Пример #3
0
        public Terminal()
        {
            InitializeComponent();

            if (sw == null)
                sw = new StreamWriter("Terminal-" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".txt");
        }
Пример #4
0
 public static void SaveTo(string filename, MailAccess mailAccess) {
     using (var streamWriter = new StreamWriter(filename, false, Encoding.UTF8)) {
         streamWriter.WriteLine(mailAccess.Server);
         streamWriter.WriteLine(mailAccess.Username);
         streamWriter.WriteLine(mailAccess.Password);
     }
 }
Пример #5
0
 static void Main(string[] args)
 {
     using (StreamWriter str = new StreamWriter(args[0]))
     {
         int a = Convert.ToInt32(args[1]);
         int b = Convert.ToInt32(args[2]);
         str.WriteLine("Parameters:");
         str.WriteLine(a);
         str.WriteLine(b);
         int min;
         if (a > b)
             min = b;
         else
             min = a;
         int i = min;
         int c = 0;
         while (i>0&&c==0)
         {
             if ((a % i == 0) && (b % i == 0))
                 c = i;
             i--;
         }
         //c = 0;
         str.WriteLine("Answers:");
         str.WriteLine(Convert.ToString(c));
         //str.WriteLine(a);
     }
 }
Пример #6
0
        // TODO: hack
        public RubyIO(RubyContext/*!*/ context, StreamReader reader, StreamWriter writer, string/*!*/ modeString)
            : this(context) {
            _mode = ParseIOMode(modeString, out _preserveEndOfLines);
            _stream = new DuplexStream(reader, writer);

            ResetLineNumbersForReadOnlyFiles(context);
        }
Пример #7
0
 public void Init()
 {
     srStrokes = new StreamReader(opt.StrokesFileName);
     srTypes = new StreamReader(opt.StrokesTypesFileName);
     srCedict = new StreamReader(opt.CedictFileName);
     swOut = new StreamWriter(opt.OutFileName);
 }
Пример #8
0
        /// <summary>
        /// Uploads a file to a given URL and verifies the HTTP request
        /// through the XMPP server (XEP-0070).
        /// </summary>
        /// <param name="uri">URI to send the file to.</param>
        /// <param name="jid">JID to send as.</param>
        /// <param name="filename">File to send.</param>
        public void Upload(string uri, string jid, string filename)
        {
            //try
            //{
            StreamReader reader = new StreamReader(filename);
            HttpWebRequest request =
                (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method = "POST";
            request.Headers.Add(HttpRequestHeader.Authorization,
                                "x-xmpp-auth jid=\"" + jid + "\"");

            StreamWriter writer = new StreamWriter(request.GetRequestStream());
            writer.Write(reader.ReadToEnd());

            reader.Close();

            request.BeginGetResponse(new AsyncCallback(ResponseCallback),
                                     request);
            writer.Close();
            // }
            // catch (WebException)
            // {
            // }
        }
Пример #9
0
        public void exportCSV(string filename)
        {
            StreamWriter tw = new StreamWriter(filename);

            tw.WriteLine("Filename;Key;Text");
            string fn;
            int i, j;
            List<string> val;
            string str;

            for (i = 0; i < LTX_Texte.Count; i++)
            {
                fn = LTX_Texte[i].Key.ToLower().Replace(".ltx","");
                val = LTX_Texte[i].Value;
                for (j = 0; j < val.Count; j++)
                {
                    str = prepareText(val[j], true);
                    if( str != "" )
                        tw.WriteLine(fn + ";" + j.ToString() + ";" + str);
                }
            }
            for (i = 0; i < DTX_Texte.Count; i++)
            {
                fn = DTX_Texte[i].Key.ToLower().Replace(".dtx","");
                val = DTX_Texte[i].Value;
                for (j = 0; j < val.Count; j++)
                {
                    str = prepareText(val[j], true);
                    if (str != "")
                        tw.WriteLine(fn + ";" + j.ToString() + ";" + str);
                }
            }

            tw.Close();
        }
        public static void Run()
        {
            // ExStart:ExtractTextFromPageRegion
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Open document
            Document pdfDocument = new Document(dataDir + "ExtractTextAll.pdf");

            // Create TextAbsorber object to extract text
            TextAbsorber absorber = new TextAbsorber();
            absorber.TextSearchOptions.LimitToPageBounds = true;
            absorber.TextSearchOptions.Rectangle = new Aspose.Pdf.Rectangle(100, 200, 250, 350);

            // Accept the absorber for first page
            pdfDocument.Pages[1].Accept(absorber);

            // Get the extracted text
            string extractedText = absorber.Text;
            // Create a writer and open the file
            TextWriter tw = new StreamWriter(dataDir + "extracted-text.txt");
            // Write a line of text to the file
            tw.WriteLine(extractedText);
            // Close the stream
            tw.Close();
            // ExEnd:ExtractTextFromPageRegion          
            
        }
Пример #11
0
        private void CheckAndChangeNewFile()
        {
            if (this.writer.BaseStream.Length >= this.maxLength)
            {                
                this.writer.Close();
                this.writer = null;

                string fileName = ESBasic.Helpers.FileHelper.GetFileNameNoPath(this.iniPath);
                string dir = ESBasic.Helpers.FileHelper.GetFileDirectory(this.iniPath);
                int pos = fileName.LastIndexOf('.');
                string extendName = null;
                string pureName = fileName;
                if (pos >=0)
                {
                    extendName = fileName.Substring(pos+1);
                    pureName = fileName.Substring(0, pos);
                }

                string newPath = null;
                for(int i=1;i<1000;i++)
                {
                    string newName = pureName + "_" + i.ToString("000");
                    if (extendName != null)
                    {
                        newName += "." + extendName;
                    }
                    newPath = dir + "\\" + newName;
                    if (!File.Exists(newPath))
                    {
                        break;
                    }
                }                
                this.writer = new StreamWriter(File.Open(newPath, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write, FileShare.Read));  
            }
        }
Пример #12
0
 /// <summary>
 /// Запись в ЛОГ-файл
 /// </summary>
 /// <param name="str"></param>
 public void WriteToLog(string str, bool doWrite = true)
 {
     if (doWrite)
     {
         StreamWriter sw = null;
         FileStream fs = null;
         try
         {
             string curDir = AppDomain.CurrentDomain.BaseDirectory;
             fs = new FileStream(curDir + "teplouchetlog.pi", FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
             sw = new StreamWriter(fs, Encoding.Default);
             if (m_vport == null) sw.WriteLine(DateTime.Now.ToString() + ": Unknown port: adress: " + m_address + ": " + str);
             else sw.WriteLine(DateTime.Now.ToString() + ": " + m_vport.GetName() + ": adress: " + m_address + ": " + str);
             sw.Close();
             fs.Close();
         }
         catch
         {
         }
         finally
         {
             if (sw != null)
             {
                 sw.Close();
                 sw = null;
             }
             if (fs != null)
             {
                 fs.Close();
                 fs = null;
             }
         }
     }
 }
Пример #13
0
    public void CreateLog(Exception ex)
    {
      try
      {
        using (TextWriter writer = new StreamWriter(_filename, false))
        {
          writer.WriteLine("Crash Log: {0}", _crashTime);

          writer.WriteLine("= System Information");
          writer.Write(SystemInfo());
          writer.WriteLine();

          writer.WriteLine("= Disk Information");
          writer.Write(DriveInfo());
          writer.WriteLine();

          writer.WriteLine("= Exception Information");
          writer.Write(ExceptionInfo(ex));
					writer.WriteLine();
					writer.WriteLine();

					writer.WriteLine("= MediaPortal Information");
					writer.WriteLine();
        	IList<string> statusList = ServiceRegistration.Instance.GetStatus();
        	foreach (string status in statusList)
        		writer.WriteLine(status);
        }
      }
      catch (Exception e)
      {
        Console.WriteLine("UiCrashLogger crashed:");
        Console.WriteLine(e.ToString());
      }
    }
Пример #14
0
        void IMapExporter.Save(string filename, Dictionary<string, System.Drawing.Rectangle> map)
        {
            // Original filename                    New filename,     ?, 2D, X         Y,        MAGIC     Width     Height
            //.\Animations\player_fall_ne_9.png		0_Animations.png, 0, 2D, 0.000000, 0.000000, 0.000000, 0.058594, 0.064453

            // copy the files list and sort alphabetically
            string[] keys = new string[map.Count];
            map.Keys.CopyTo(keys, 0);
            List<string> outputFiles = new List<string>(keys);
            outputFiles.Sort();

            using (StreamWriter writer = new StreamWriter(filename))
            {
                foreach (var image in outputFiles)
                {
                    // get the destination rectangle
                    Rectangle destination = map[image];

                    // write out the destination rectangle for this bitmap
                    //line = item.SourceName + "\t\t" + item.Destination + ", 0, 2D, " + item.ScaledRect.X.ToString("0.000000") + ", " +
                    //item.ScaledRect.Y.ToString("0.000000") + ", 0.000000, " + item.ScaledRect.Width.ToString("0.000000") + ", " + item.ScaledRect.Height.ToString("0.000000");

                    writer.WriteLine(string.Format(
                        "{0}\t\t{1}, 0, 2D, {2:F5}, {3:F5}, 0.00000, {4:F5}, {5:F5}",
                     	image,
                        Path.GetFileNameWithoutExtension(filename)+".png",
                     	(float)destination.X / atlasWidth,
                        (float)destination.Y / atlasHeight,
                        (float)destination.Width / atlasWidth,
                        (float)destination.Height / atlasHeight));
                }
            }
        }
Пример #15
0
        protected override async void Write(Core.LogEventInfo logEvent)
        {

            var request = (HttpWebRequest) WebRequest.Create(ServerUrl);
            request.ContentType = "application/json; charset=utf-8";
            request.Method = "POST";
            var requestWriter = new StreamWriter(request.GetRequestStream());
            
            requestWriter.Write("{ "
                                + "\"version\": " + "\"" + "1.0" + "\",\n"
                                + "\"host\": " + "\"" + AndroidId + "\",\n"
                                + "\"short_message\": " + "\"" + logEvent.FormattedMessage + "\",\n"
                                + "\"full_message\": " + "\"" + logEvent.FormattedMessage + "\",\n"
                                + "\"timestamp\": " + "\"" + DateTime.Now.ToString(CultureInfo.InvariantCulture) +
                                "\",\n"
                                + "\"level\": " + "\"" +
                                logEvent.Level.Ordinal.ToString(CultureInfo.InvariantCulture) + "\",\n"
                                + "\"facility\": " + "\"" + "NLog Android Test" + "\",\n"
                                + "\"file\": " + "\"" + Environment.CurrentDirectory + "AndroidApp" + "\",\n"
                                + "\"line\": " + "\"" + "123" + "\",\n"
                                + "\"Userdefinedfields\": " + "{}" + "\n"
                                + "}");

            requestWriter.Close();

            LastResponseMessage = (HttpWebResponse) request.GetResponse();
        }
Пример #16
0
        public void Trace(NetState state)
        {
            try
            {
                string path = Path.Combine(Paths.LogsDirectory, "packets.log");                

                using (StreamWriter sw = new StreamWriter(path, true))
                {
                    sw.BaseStream.Seek(sw.BaseStream.Length, SeekOrigin.Begin);

                    byte[] buffer = _data;

                    if (_data.Length > 0)
                        Tracer.Warn(string.Format("Unhandled packet 0x{0:X2}", _data[0]));

                    buffer.ToFormattedString(buffer.Length, sw);

                    sw.WriteLine();
                    sw.WriteLine();
                }
            }
            catch (Exception e)
            {
                Tracer.Error(e);
            }
        }
Пример #17
0
 private void WriteToFSLocation(string path, string value)
 {
     using (StreamWriter sw = new StreamWriter(path))
     {
         sw.Write(value);
     }
 }
Пример #18
0
        private void SaveLastCode()
        {
            string filename = Path.Combine(localPath, "TestApp.os");
            using (var writer = new StreamWriter(filename, false, Encoding.UTF8))
            {
                // первой строкой запишем имя открытого файла
                writer.Write("//");  // знаки комментария, чтобы сохранить код правильным
                writer.WriteLine(_currentDocPath);
                // второй строкой - признак изменённости
                writer.Write("//");
                writer.WriteLine(_isModified);

                args.Text = args.Text.TrimEnd('\r', '\n');

                // запишем аргументы командной строки
                writer.Write("//");
                writer.WriteLine(args.LineCount);

                for (var i = 0; i < args.LineCount; ++i )
                {
                    string s = args.GetLineText(i).TrimEnd('\r', '\n');
                    writer.Write("//");
                    writer.WriteLine(s);
                }

                // и потом сам код
                writer.Write(txtCode.Text);
            }
        }
Пример #19
0
 private void  InitBlock()
 {
     System.IO.StreamWriter temp_writer;
     temp_writer = new System.IO.StreamWriter(System.Console.OpenStandardOutput(), System.Console.Out.Encoding);
     temp_writer.AutoFlush = true;
     debugStream = temp_writer;
 }
Пример #20
0
 //Write the power output file
 //Output is 100 numbers separated by tabs, representing the power at 1% threshold, 2%, 3%... 100%
 public static void powerOutput(string filenameStub,int m, int startRep, int endRep)
 {
     int[] ranks = new int[endRep - startRep + 1];
     double[] power = new double[100];
     int attributes = 1000;
     for (int rep = startRep; rep <= endRep; rep++)
     {
         string filename = filenameStub + rep + ".txt";
         List<ReliefUtils.SNP> SNPs = FileUtilities.Utils.ReadReliefOutput(filename);
         attributes = SNPs.Count;
         //Sort SNPs by descending score
         SNPs.Sort(delegate(ReliefUtils.SNP S1, ReliefUtils.SNP S2) { return S2.W.CompareTo(S1.W); });
         //Find the lower ranked of the 2 informative SNPs (0 and 1)
         int rank0 = SNPs.FindIndex(delegate(ReliefUtils.SNP s) { return s.ID == 0; });
         int rank1 = SNPs.FindIndex(delegate(ReliefUtils.SNP s) { return s.ID == 1; });
         ranks[rep-startRep] = Math.Max(rank0, rank1);
     }
     string powerFilename = filenameStub + startRep + "to" + endRep + ".power.txt";
     StreamWriter powerOutput = new StreamWriter(powerFilename);
     //Find the power by percentiles (% of reps with both SNPs above threshold)
     for (int percentile = 1; percentile <= 100; percentile++)
     {
         int passed = 0;
         for (int rep = 0; rep <= endRep - startRep; rep++)
         {
             if (ranks[rep] <= (attributes * percentile / 100.0))
                 passed++;
         }
         power[percentile - 1] = passed / (endRep - startRep + 1.0);
         Console.WriteLine("Power at " + percentile + "%: " + power[percentile - 1]);
         powerOutput.Write(power[percentile - 1]);
         if (percentile != 100) powerOutput.Write("\t");
     }
     powerOutput.Close();
 }
        public static void Main()
        {
            var url = new Uri(ApiUrl + "?auth-id=" + AuthenticationID + "&auth-token=" + AuthenticationToken);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";

            using (var stream = request.GetRequestStream())
            using (var writer = new StreamWriter(stream))
                writer.Write(RequestPayload);

            using (var response = request.GetResponse())
            using (var stream = response.GetResponseStream())
            using (var reader = new StreamReader(stream))
            {
                var rawResponse = reader.ReadToEnd();
                Console.WriteLine(rawResponse);

                // Suppose you wanted to use Json.Net to pretty-print the response (delete the next two lines if not):
                // Json.Net: http://http://json.codeplex.com/
                dynamic parsedJson = JsonConvert.DeserializeObject(rawResponse);
                Console.WriteLine(JsonConvert.SerializeObject(parsedJson, Formatting.Indented));

                // Or suppose you wanted to deserialize the json response to a defined structure (defined below):
                var candidates = JsonConvert.DeserializeObject<CandidateAddress[]>(rawResponse);
                foreach (var address in candidates)
                    Console.WriteLine(address.DeliveryLine1);
            }

            Console.ReadLine();
        }
Пример #22
0
        private async void btnSave_Click(object sender, EventArgs e)
        {
            if (tbData.Text.Length <= 0)
            {
                MessageBox.Show(@"No text entered", @"Error!", MessageBoxButtons.OK);
                return;
            }

            try
            {
                //create dir if it does not exists
                while (!Directory.Exists(PathToFile))
                {
                    Directory.CreateDirectory(PathToFile);
                }

                using (StreamWriter fs = new StreamWriter(Path.Combine(PathToFile, FileName), false))
                {
                    await fs.WriteAsync(tbData.Text);
                }
            }
            catch (IOException ex)
            {
                //catch error
                MessageBox.Show(ex.Message, @"Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #23
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.TextLength != 0)
            {
                string file = Path.Combine(BESFolder, textBox1.Text + ".cbes");

                if (File.Exists(file))
                    File.Delete(file);

                StreamWriter writer = new StreamWriter(file);
                writer.WriteLine(form.GetInitial());
                writer.WriteLine(form.GetExpand());
                writer.WriteLine(form.GetRounds());
                writer.WriteLine(form.GetLeftoff());
                writer.WriteLine(form.GetKey());
                writer.WriteLine(form.GetCipherMode());
                writer.WriteLine(form.GetSeedFunction());
                writer.WriteLine(form.GetGenerationMode());
                writer.Close();
                writer.Dispose();

                RefreshElements();

                this.Close();
            }
        }
Пример #24
0
        /// <summary>
        /// A method that takes a Query, and writes a log of that Query and when it was
        /// executed to a file on disk. All Queries executed on a given day are written
        /// to a file with that date as the filename. There's not a massive amount
        /// of complex logic here, just StreamWriters.
        /// </summary>
        /// <param name="query">The Query object to log.</param>
        /// <param name="remoteQuery">Whether or not this was a query processed on the server.</param>
        internal static void LogToDisk(Query query, bool remoteQuery)
        {
            string directoryPath = ConfigurationManager.AppSettings["LoggingDirectory"];
            string queryLogString;
            if (remoteQuery)
            {
                queryLogString = query.ToString() + " processed on server";

            }
            else
            {
                queryLogString = query.ToString();
            }

            if(Directory.Exists(directoryPath))
            {
                DateTime currentDay = DateTime.Today.Date;
                if (File.Exists(directoryPath + @"\" + currentDay.ToString(DATE_FORMAT) + ".txt"))
                {

                    using (StreamWriter fileWriter = new StreamWriter(directoryPath + @"\" + currentDay.ToString(DATE_FORMAT) + ".txt", true))
                    {
                        fileWriter.WriteLine(queryLogString);
                    }
                }
                else
                {
                    using (StreamWriter fileWriter = new StreamWriter(directoryPath + @"\" + currentDay.ToString(DATE_FORMAT) + ".txt", false))
                    {
                        fileWriter.WriteLine(queryLogString);
                    }
                }
            }
        }
Пример #25
0
        public static void ConvertFormat(string strInputFile, string strOutputFile)
        {
            StreamReader sr = new StreamReader(strInputFile);
            StreamWriter sw = new StreamWriter(strOutputFile);
            string strLine = null;

            while ((strLine = sr.ReadLine()) != null)
            {
                strLine = strLine.Trim();

                string[] items = strLine.Split();
                foreach (string item in items)
                {
                    int pos = item.LastIndexOf('[');
                    string strTerm = item.Substring(0, pos);
                    string strTag = item.Substring(pos + 1, item.Length - pos - 2);

                    sw.WriteLine("{0}\t{1}", strTerm, strTag);
                }
                sw.WriteLine();
            }

            sr.Close();
            sw.Close();
        }
Пример #26
0
        static void UnhandledException( object sender, UnhandledExceptionEventArgs e )
        {
            // So we don't get the normal unhelpful crash dialog on Windows.
            Exception ex = (Exception)e.ExceptionObject;
            string error = ex.GetType().FullName + ": " + ex.Message + Environment.NewLine + ex.StackTrace;
            bool wroteToCrashLog = true;
            try {
                using( StreamWriter writer = new StreamWriter( crashFile, true ) ) {
                    writer.WriteLine( "--- crash occurred ---" );
                    writer.WriteLine( "Time: " + DateTime.Now.ToString() );
                    writer.WriteLine( error );
                    writer.WriteLine();
                }
            } catch( Exception ) {
                wroteToCrashLog = false;
            }

            string message = wroteToCrashLog ?
                "The cause of the crash has been logged to \"" + crashFile + "\". Please consider reporting the crash " +
                "(and the circumstances that caused it) to github.com/UnknownShadow200/ClassicalSharp/issues" :

                "Failed to write the cause of the crash to \"" + crashFile + "\". Please consider reporting the crash " +
                "(and the circumstances that caused it) to github.com/UnknownShadow200/ClassicalSharp/issues" +
                Environment.NewLine + Environment.NewLine + error;

            MessageBox.Show( "Oh dear. ClassicalSharp has crashed." + Environment.NewLine +
                            Environment.NewLine + message, "ClassicalSharp has crashed" );
            Environment.Exit( 1 );
        }
Пример #27
0
        public static void Extract(Category category)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Extract");
            if(!Directory.Exists(path))
                Directory.CreateDirectory(path);

            pset.Clear();
            pdic.Clear();
            string downPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", "Down", category.Name);
            string fileName = string.Format(@"{0}\{1}.txt", path, category.Name);

            StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);
            for (int i = category.DownPageCount; i >= 1; i--)
            {
                string htmlFileName = string.Format(@"{0}\{1}.html", downPath, i);
                if (!File.Exists(htmlFileName))
                    Logger.Instance.Write(string.Format("{0}-{1}.html-not exist", category.Name, i));
                StreamReader sr = new StreamReader(htmlFileName, Encoding.UTF8);
                string text = sr.ReadToEnd();
                sr.Close();

                var action = CreateAction(category.Type);
                if (action == null) continue;

                Extract(text, sw, category.Name,category.DbName, action);
            }
            sw.Close();

            Console.WriteLine("{0}:Extract Data Finished!", category.Name);
        }
Пример #28
0
 private void button3_Click(object sender, EventArgs e)
 { 
     if (button3.Text=="Cancel")
         this.Close();
     else
     {
         if (listBox1.SelectedIndex < 0)
         {
             return;
         }
         else
         {
             string str = listBox1.SelectedItem.ToString();
             string str1 = string.Format("learning/" + str + ".txt");
             StreamWriter sw = new StreamWriter(str1, false, Encoding.UTF8);
             foreach (string line in richTextBox1.Lines)
             {
                 sw.WriteLine(line);
             }
             sw.Close();
             button3.Text = "Cancel";
             richTextBox1.ReadOnly = true;
             MessageBox.Show("Đã lưu " + str);
         }
     }
 }
        private void ChangeCopyright()
        {
            UpdateLabel("searching for rotmg version display string");
            Dictionary<string, string> files = new Dictionary<string, string>();
            string filetext = String.Empty;

            foreach (string path in this.files)
            {
                using (StreamReader rdr = new StreamReader(File.Open(path, FileMode.Open)))
                {
                    filetext = rdr.ReadToEnd();
                    if (filetext.Contains(ROTMG_VERSION_TEXT))
                    {
                        UpdateLabel("request found!");
                        files.Add(path, filetext);
                    }
                }
            }

            foreach (var file in files)
            {
                UpdateLabel("replacing version text");
                filetext = file.Value.Replace(ROTMG_VERSION_TEXT, "<font color='#00CCFF'>Fabiano Swagger of Doom</font> #{VERSION}.{MINORVERSION}");
                filetext = filetext.Replace("{MINOR}", "{MINORVERSION}");
                using (StreamWriter wtr = new StreamWriter(file.Key, false))
                    wtr.Write(filetext);
            }
            UpdateLabel("Version Display: Done!");
        }
Пример #30
0
        public static string EncryptString(string plainText)
        {
            byte[] encrypted;

            AesCryptoServiceProvider provider = createAesProvider();

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = provider.CreateEncryptor(provider.Key, null); // null IV, because ECB mode

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
            // Return the encrypted bytes from the memory stream.
            return encoding.GetString(encrypted);
        }