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(); }
/// <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; } } } }
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); } }
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); } }
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); } }
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); } }
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(); }
private void ExportToExcel() { DgStats.SelectAllCells(); DgStats.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader; ApplicationCommands.Copy.Execute(null, DgStats); var stats = (string) Clipboard.GetData(DataFormats.CommaSeparatedValue); //String result = (string)Clipboard.GetData(DataFormats..Text); DgStats.UnselectAllCells(); DgUnmatched.SelectAllCells(); DgUnmatched.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader; ApplicationCommands.Copy.Execute(null, DgUnmatched); var unmatched = (string) Clipboard.GetData(DataFormats.CommaSeparatedValue); DgUnmatched.UnselectAllCells(); var saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = string.Format("{0}.Reconcile.csv", Path.GetFileName(_vm.BankFile.FilePath)); if (saveFileDialog.ShowDialog() == true) { var file = new StreamWriter(saveFileDialog.FileName); file.WriteLine(stats); file.WriteLine(""); file.WriteLine(unmatched); file.Close(); } }
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 ); } }
public void comprobarGanador(StreamWriter sw) { // Resolvemos la jugada if ((jugada1 == "piedra" && jugada2 == "piedra") || (jugada1 == "papel" && jugada2 == "papel") || (jugada1 == "tijera" && jugada2 == "tijera")) { sw.WriteLine("#OK#empate#"); sw.Flush(); } else if ((jugada1 == "piedra" && jugada2 == "tijera") || (jugada1 == "tijera" && jugada2 == "papel") || (jugada1 == "papel" && jugada2 == "piedra")) { sw.WriteLine("#OK#ganador:" + jugador1 + "#"); puntos1++; sw.Flush(); } else if ((jugada2 == "piedra" && jugada1 == "tijera") || (jugada2 == "tijera" && jugada1 == "papel") || (jugada2 == "papel" && jugada1 == "piedra")) { sw.WriteLine("#OK#ganador:" + jugador2 + "#"); puntos2++; sw.Flush(); } //dormimos el thread 1 segundo para que de tiempo a que el otro jugador analice el resultado //antes de borrar las jugadas Thread.Sleep(1000); jugada1 = ""; jugada2 = ""; }
private static void WritePoints(StreamWriter writer, IEnumerable<Point> points, int count) { int attributes = 0, index = 0; var first = points.FirstOrDefault(); if (first.Attributes != null) { attributes = first.Attributes.Length; } writer.WriteLine("{0} {1} {2} {3}", count, 2, attributes, 1); foreach (var item in points) { // Vertex number, x and y coordinates. writer.Write("{0} {1} {2}", index, item.X.ToString(Util.Nfi), item.Y.ToString(Util.Nfi)); // Write attributes. for (int j = 0; j < attributes; j++) { writer.Write(" {0}", item.Attributes[j].ToString(Util.Nfi)); } // Write the boundary marker. writer.WriteLine(" {0}", item.Boundary); index++; } }
static void Main(string[] args) { DateTime now = DateTime.Now; string reportPath = String.Format(ReportPath, now); const int Count = 100; double total = 0; for (int i=0; i<Count; i++) { using (StreamWriter writer = new StreamWriter(reportPath, false, Encoding.UTF8)) { writer.WriteLine(HeaderMessage, now); Stopwatch watch = Stopwatch.StartNew(); UnitTests.StronglyTyped.RunTest(writer, UnitTestsFolder, OutputFolder); UnitTests.JsonText.RunTest(writer, UnitTestsFolder, OutputFolder); watch.Stop(); writer.WriteLine(UnitTests.JsonText.Seperator); writer.WriteLine("Elapsed: {0} ms", watch.Elapsed.TotalMilliseconds); total += watch.Elapsed.TotalMilliseconds; } } Console.WriteLine("Average after {1} tries: {0} ms", total/Count, Count); Process process = new Process(); process.StartInfo.FileName = "notepad.exe"; process.StartInfo.Arguments = reportPath; process.Start(); }
static void Main(string[] args) { var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var items = Directory.GetFiles(dir, "*.jpg").ToList(); items.AddRange(Directory.GetFiles(dir, "*.jpeg")); items.AddRange(Directory.GetFiles(dir, "*.gif")); items.AddRange(Directory.GetFiles(dir, "*.png")); //rename all the filesthat are samples const string SAM = "sample-"; foreach (var item in items.Select(x => Path.GetFileName(x)).Where(x => x.StartsWith(SAM, StringComparison.CurrentCultureIgnoreCase))) { var newName = Path.Combine(dir, item.Substring(SAM.Length, item.Length-SAM.Length)); var oldName = Path.Combine(dir, item); if (!items.Contains(newName)) File.Copy(oldName, newName); File.Delete(oldName); } using (var sw = new StreamWriter(Path.Combine(dir, "dir.js"), false)) { sw.WriteLine("var IMAGES = ["); foreach (var item in items) sw.WriteLine(" \"{0}\",", Path.GetFileName(item)); //seems we don't have to worry about the extra comma sw.WriteLine("];"); } }
public static void ReplaceStringLiteralsWithVariables(string filterPath, string varSourcePath, IEnumerable<string> sourcePaths, IEnumerable<string> macros) { string varClassName = Path.GetFileNameWithoutExtension(varSourcePath); var filter = new HashSet<string>(File.ReadAllLines(filterPath, Encoding.Default)); var str2VarName = new Dictionary<string, string>(1024); foreach (var path in sourcePaths) { var oldText = File.ReadAllText(path, Encoding.Default); var newText = RoslynTool.CodeTransform.ReplaceStringLiteralsWithVariables(oldText, macros, (line, column, s) => { if (!filter.Contains(string.Format("{0}({1},{2}):{3}", path, line, column, s))) return null; string varName; if (str2VarName.TryGetValue(s, out varName)) return varName; varName = string.Format("{0}.kString_{1}", varClassName, str2VarName.Count); str2VarName.Add(s, varName); return varName; }); if (oldText != newText) File.WriteAllText(path, newText, Encoding.Default); } using (var varFile = new StreamWriter(File.Create(varSourcePath, 4 * 1024), Encoding.Default)) { varFile.WriteLine(string.Format("public static class {0} {{", varClassName)); foreach (var kv in str2VarName) { varFile.WriteLine("\tpublic const string {0} = {1};", kv.Value.Split('.').Last(), kv.Key); } varFile.WriteLine("}"); } }
public bool Delete(Range range) { if (range.LineRange.Length == 0) { return true; } string fileContents = File.ReadAllText(_filename); using (StringReader reader = new StringReader(fileContents)) using (TextWriter writer = new StreamWriter(File.Open(_filename, FileMode.Create))) { string lineText; if (SeekTo(reader, writer, range, out lineText)) { writer.WriteLine(lineText.Substring(0, range.LineRange.Start) + lineText.Substring(range.LineRange.Start + range.LineRange.Length)); } lineText = reader.ReadLine(); while (lineText != null) { writer.WriteLine(lineText); lineText = reader.ReadLine(); } } return true; }
public static void RunTests() { StreamWriter results = new StreamWriter(@"../../results.txt"); bool testcaseResult; results.WriteLine("-------------- Custom Handler\n"); for (var i = 0; i < Testcases.Length; i++) { var sw = Stopwatch.StartNew(); testcaseResult = CustomHandler.CheckText(Testcases[i]); sw.Stop(); results.Write("Testcase N{0}: {1}\n" + "Solution runtime summary: {2} ticks ({3} ms)\n\n", i + 1, testcaseResult, sw.ElapsedTicks, sw.ElapsedMilliseconds); } results.WriteLine("-------------- Regex Handler\n"); for (var i = 0; i < Testcases.Length; i++) { var sw = Stopwatch.StartNew(); testcaseResult = RegexHandler.CheckText(Testcases[i]); sw.Stop(); results.Write("Testcase N{0}: {1}\n" + "Solution runtime summary: {2} ticks ({3} ms)\n\n", i + 1, testcaseResult, sw.ElapsedTicks, sw.ElapsedMilliseconds); } results.Close(); }
/// <summary> /// Initializes the log using the file defnied in the Filename property. /// </summary> public static void Init() { lock (Locker) { if (!IsInitialized) { try { Logger = File.AppendText(Filename); Logger.WriteLine("---------------------------------------------------------------------------------"); Logger.WriteLine("{0}\t{1}", DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss.fff"), "DirectOutput Logger initialized"); Version V = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; DateTime BuildDate = new DateTime(2000, 1, 1).AddDays(V.Build).AddSeconds(V.Revision * 2); Logger.WriteLine("{0}\t{1}", DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss.fff"), "DirectOutput Version {0} as of {1}".Build(V.ToString(), BuildDate.ToString("yyyy.MM.dd HH:mm"))); IsOk = true; Debug("Writting of debug log messages is enabled"); } catch { IsOk = false; } IsInitialized = true; } } }
/// <summary> /// This method is used to write exception details to file. /// </summary> /// <param name="ex"></param> public static void WriteLog(Exception ex) { try { string filename = m_baseDir + "ExceptionDirectory\\" + GetFilenameYYYMMDD("_LOG", ".log"); System.IO.StreamWriter sw = new System.IO.StreamWriter(filename, true); XElement xmlEntry = new XElement("logEntry", new XElement("Date", System.DateTime.Now.ToString()), new XElement("Exception", new XElement("Source", ex.Source), new XElement("Message", ex.Message), new XElement("Stack", ex.StackTrace) ) ); if (ex.InnerException != null) { xmlEntry.Element("Exception").Add( new XElement("InnerException", new XElement("Source", ex.InnerException.Source), new XElement("Message", ex.InnerException.Message), new XElement("Stack", ex.InnerException.StackTrace)) ); } sw.WriteLine(xmlEntry); sw.WriteLine(""); sw.WriteLine("**************************************************************************"); sw.Close(); } catch (Exception) { } }
private void button1_Click(object sender, EventArgs e) { ClickSound = new SoundPlayer(spath + label5.Text + "Resources" + label5.Text + "Sound" + label5.Text + "clickSound.wav"); ClickSound.Play(); if (comboBox2.SelectedItem != null) { directoryLabel.Text = sqpath + label5.Text + "Resources" + label5.Text + "logico01.txt"; TextWriter tw = new StreamWriter(directoryLabel.Text); int x = int.Parse(comboBox2.SelectedItem.ToString()); // проверка дали въведения отговор е верен if (x == 11) { tw.WriteLine("3"); // записване в текстовия файл } else { if (x == 20) tw.WriteLine("2"); else if (x == 9) tw.WriteLine("1"); else tw.WriteLine("0"); } MessageBox.Show("Благодаря за вашия отговор."); tw.Close(); Close(); } }
public void Guardar(Senial senial) { string _linea_dato = ""; string _fecha = senial.fecha_adquisicion.ToString ("yyyy MMMMM dd"); string _cantidad = senial.CantidadValores().ToString(); string _id = senial.Id.ToString (); string _nombre = _ubicacion + "/" + _id + " - " + _fecha + ".txt"; try { using (StreamWriter _archivo = new StreamWriter(_nombre)) { string cabecera = _id + ";" + _fecha + ";" + _cantidad + ";"; _archivo.WriteLine(cabecera); for (int i = 1; i <= senial.CantidadValores(); i++) { _linea_dato = i.ToString() + ";" + senial.ObtenerValor(i - 1).ToString() + ";"; _archivo.WriteLine(_linea_dato); } this.Trazar(senial, "Se guardo la señal"); this.Auditar(senial, senial.GetType().ToString()); } } catch (Exception e) { Console.WriteLine(e.Message); this.Trazar(senial, e.Message); } }
private static void WriteDeleteView(SchemaMigrationContext context, ProcedureDefinition procedure, StreamWriter output) { if ( context.FromDatabaseType == DatabaseType.SqlServer) output.WriteLine("\t\t\tExecute.WithDatabaseType(DatabaseType.SqlServer).Sql(\"DROP PROCEDURE [{0}].[{1}]\");", procedure.SchemaName, procedure.Name); else output.WriteLine("\t\t\tExecute.WithDatabaseType(DatabaseType.{0}).Sql(\"DROP PROCEDURE {1}\");", context.FromDatabaseType, procedure.Name); }
/// <summary> /// /// </summary> /// <remarks> /// SocketException is resolved at higher level in the /// RemoteObjectProxyProvider.ProxyInterceptor.Intercept() method. /// </remarks> /// <param name="command"></param> /// <param name="data"></param> /// <returns></returns> /// <exception cref="System.Net.Sockets.SocketException"> /// When it is not possible to connect to the server. /// </exception> public string Request(string command, string[] data) { var client = new System.Net.Sockets.TcpClient(ServerAddress.IPAddress.ToString(), ServerAddress.Port); using (var clientStream = client.GetStream()) { var sw = new StreamWriter(clientStream); command = command .Replace("\r", TcpServer.CarriageReturnReplacement) .Replace("\n", TcpServer.LineFeedReplacement); sw.WriteLine(command); sw.WriteLine(data.Length.ToString()); foreach (string item in data) { string encodedItem = item .Replace("\r", TcpServer.CarriageReturnReplacement) .Replace("\n", TcpServer.LineFeedReplacement); sw.WriteLine(encodedItem); } sw.Flush(); var sr = new StreamReader(clientStream); string result = sr.ReadLine(); if (result != null) { result = result .Replace(TcpServer.CarriageReturnReplacement, "\r") .Replace(TcpServer.LineFeedReplacement, "\n"); } return result; } }
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 ); }
public static void GenerateIntoClass( String targetFile, String @namespace, String classDeclaration, Action<StringBuilder> logic) { var buffer = new StringBuilder(); logic(buffer); using (var targetFileWriter = new StreamWriter(targetFile)) { targetFileWriter.WriteLine(Constants.CodegenDisclaimer); targetFileWriter.WriteLine(); var textGeneratedIntoClass = typeof(Helpers).Assembly.ReadAllText("Truesight.TextGenerators.Core.TextGeneratedIntoClass.template"); textGeneratedIntoClass = textGeneratedIntoClass .Replace("%NAMESPACE_NAME%", @namespace) .Replace("%CLASS_DECLARATION%", classDeclaration) .Replace("%GENERATED_TEXT%", buffer.ToString()); if (classDeclaration.Contains("enum") || classDeclaration.Contains("interface")) { textGeneratedIntoClass = textGeneratedIntoClass .Replace(" [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]" + Environment.NewLine, ""); } targetFileWriter.Write(textGeneratedIntoClass); } }
internal static void createWikiBaseCategories(string catLabel, StreamWriter file) { file.WriteLine("<!-- category " + catLabel + "-->"); file.WriteLine("<page><title>Category:" + SecurityElement.Escape(catLabel) + "</title><revision><contributor><username>Shura</username><id>5</id></contributor><minor/><text xml:space= \"preserve\">"); file.WriteLine("[[Category:Classnames]]"); file.WriteLine("</text></revision></page>"); }
public void Run() { using (var reader = new StreamReader("jobs.txt")) using (var writer = new StreamWriter("output.txt")) { var jobs = new List<Job>(); reader.ReadLine(); while (true) { string row = reader.ReadLine(); if (row == null) { break; } var parts = row.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); var numbers = parts.Select(x => int.Parse(x, CultureInfo.InvariantCulture)).ToArray(); jobs.Add(new Job(numbers[0], numbers[1])); } var weightedSum1 = JobScheduler.GetWeightedSumOfCompletionTimes(jobs, JobScheduler.CompareByDifference); writer.WriteLine(weightedSum1); var weightedSum2 = JobScheduler.GetWeightedSumOfCompletionTimes(jobs, JobScheduler.CompareByRatio); writer.WriteLine(weightedSum2); } }
private void saveData() { TextWriter tw = new StreamWriter("penny.settings"); if (checkBox1.Checked) tw.WriteLine("Enabled"); else tw.WriteLine("Disabled"); tw.Close(); }
public static void Log(LogFormat log, string fileName) { string filePath = string.Format("{0}{1}.csv", _logPath, fileName); bool fileExists = false; lock (lockMe) { if (File.Exists(filePath)) { fileExists = true; } using (StreamWriter sw = new StreamWriter(filePath, true)) { if (!fileExists) { sw.WriteLine("IN DATE TIME,FlawID,FlawName,Flaw Y value(M),Flaw X value(M),JobID,OUT DATA,TYPE,Flaw Y value(mm),Flaw X value(mm),OUT DATA TIME,STATUS"); } string output = string.Format("{0},{1},,{2},{3},{4}", log.InputDateTime, log.InputData, log.OutputData, log.OutputDateTime, log.Status); sw.WriteLine(output); sw.Close(); } } }
public bool Insert(Range range, string text, bool addNewline) { if (text.Length == 0) { return true; } string fileContents = File.ReadAllText(_filename); using (StringReader reader = new StringReader(fileContents)) using (TextWriter writer = new StreamWriter(File.Open(_filename, FileMode.Create))) { string lineText; if (SeekTo(reader, writer, range, out lineText)) { writer.WriteLine(lineText.Substring(0, range.LineRange.Start) + text + (addNewline ? Environment.NewLine : string.Empty) + lineText.Substring(range.LineRange.Start)); } lineText = reader.ReadLine(); while (lineText != null) { writer.WriteLine(lineText); lineText = reader.ReadLine(); } } return true; }
private void Rescore(string icResultFilePath, string outputFilePath) { var parser = new TsvFileParser(icResultFilePath); var sequences = parser.GetData("Sequence"); var scanNums = parser.GetData("ScanNum").Select(s => Convert.ToInt32(s)).ToArray(); var charges = parser.GetData("Charge").Select(c => Convert.ToInt32(c)).ToArray(); var compositions = parser.GetData("Composition").Select(Composition.Parse).ToArray(); var modIndex = parser.GetHeaders().IndexOf("Modifications"); var rows = parser.GetRows(); var headers = parser.GetHeaders(); using (var writer = new StreamWriter(outputFilePath)) { writer.WriteLine("{0}\t{1}", string.Join("\t", headers), IcScores.GetScoreNames()); for (var i = 0; i < parser.NumData; i++) { var row = rows[i]; var seqStr = sequences[i]; var charge = charges[i]; var scanNum = scanNums[i]; var composition = compositions[i]; var scores = _topDownScorer.GetScores(AminoAcid.ProteinNTerm, seqStr, AminoAcid.ProteinCTerm, composition, charge, scanNum); var token = row.Split('\t'); for (var j = 0; j < token.Length; j++) { if(j != modIndex) writer.Write(token[j]+"\t"); else writer.Write("["+scores.Modifications+"]"+"\t"); } writer.WriteLine(scores); } } }
private void WriteToServerStream(string msg) { if (_outgoingStream != null && _ircTcpClient.Connected) { irclog?.WriteLine(msg); _outgoingStream.WriteLine(msg); } }
private void 끝내기ToolStripMenuItem_Click(object sender, EventArgs e) { try { if (modified) { DialogResult answer = MessageBox.Show("변경된 내용을 저장하시겠습니까?", "저장", MessageBoxButtons.YesNoCancel); if (answer == DialogResult.Yes) { if (file_name) { System.IO.StreamWriter fs = new System.IO.StreamWriter(name, false, System.Text.Encoding.Default); fs.WriteLine(textBox1.Text); fs.Close(); modified = false; } else { if (saveFileDialog1.ShowDialog() == DialogResult.OK) { name = saveFileDialog1.FileName; System.IO.StreamWriter fs = new System.IO.StreamWriter(name, false, System.Text.Encoding.Default); fs.WriteLine(textBox1.Text); fs.Close(); modified = false; file_name = true; } } } } Application.Exit(); } catch { MessageBox.Show("끝내기를 하는 도중 이상이 발생하였습니다.", "에러", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
// Pour sauvegarder dans un fichier texte public void Save(bool append = false) { int i = 0; System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, append); foreach (SaveTransform t in SaveTransforms) { // On le numéro de la sauvegarde, le temps et sa rotation sw.WriteLine("#" + i); sw.WriteLine(t.time); sw.WriteLine(t.rot.x); sw.WriteLine(t.rot.y); sw.WriteLine(t.rot.z); sw.WriteLine(t.rot.w); i += 1; } sw.Close(); }
private void Export(object sender, RoutedEventArgs e) { dataGrid.SelectAllCells(); dataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader; ApplicationCommands.Copy.Execute(null, dataGrid); String resultat = (string)System.Windows.Clipboard.GetData(System.Windows.DataFormats.CommaSeparatedValue); String result = (string)System.Windows.Clipboard.GetData(System.Windows.DataFormats.Text); dataGrid.UnselectAllCells(); //System.Windows.MessageBox.Show("Enter Export path"); System.Windows.Forms.FolderBrowserDialog fbd = new FolderBrowserDialog(); //fbd.ShowNewFolderButton = true; fbd.SelectedPath = ""; fbd.ShowDialog(); fbd.Description = "Select the directory to save the records."; //System.IO.StreamWriter file1 = new System.IO.StreamWriter(@"C:\Trade Blotter\Records.xls"); /* * file1.WriteLine(result.Replace(',', ' ')); * file1.Close(); */ if (string.Equals(fbd.SelectedPath, "")) { // Prompt that there was no entry. // Do nothing. } else { string sample = fbd.SelectedPath; System.IO.StreamWriter file1 = new System.IO.StreamWriter(@"" + sample + "/Records.xls"); file1.WriteLine(result.Replace(',', ',')); //file1.WriteLine(); file1.Close(); System.Windows.MessageBox.Show(" Exporting DataGrid data to Excel file created.xls"); } }
protected void ExportTextFile(String sStoredProcedure) { Data da = new Data(); List <string> sParams = new List <string>(); sParams.Clear(); DataTable dt = new DataTable(); SqlDataReader objDataReader = da.ExecuteReader(sStoredProcedure, sParams); dt.Load(objDataReader); if (dt.Rows.Count > 0) { //Build the Text file data. string txt = string.Empty; using (System.IO.StreamWriter file = new System.IO.StreamWriter(_dataPath)) { foreach (DataRow row in dt.Rows) { txt = ""; foreach (DataColumn column in dt.Columns) { //Add the Data rows. txt += row[column.ColumnName].ToString() + "\t"; } // Remove last tab txt = txt.Remove(txt.Length - 1, 1); file.WriteLine(txt); } } } }
protected void Session_Start(object sender, EventArgs e) { Application.Lock(); Application["CurrentUsers"] = System.Convert.ToInt32(Application["CurrentUsers"]) + 1; Application.UnLock(); int count_visit = 0; //Kiểm tra file count_visit.txt nếu không tồn tại thì if (System.IO.File.Exists(Server.MapPath("/count_visit.txt")) == false) { count_visit = 1; } // Ngược lại thì else { // Đọc dử liều từ file count_visit.txt System.IO.StreamReader read = new System.IO.StreamReader(Server.MapPath("/count_visit.txt")); count_visit = int.Parse(read.ReadLine()); read.Close(); // Tăng biến count_visit thêm 1 count_visit++; } // khóa m Application.Lock(); // gán biến Application count_visit Application["count_visit"] = count_visit; // Mở khóa website Application.UnLock(); // Lưu dử liệu vào file count_visit.txt System.IO.StreamWriter writer = new System.IO.StreamWriter(Server.MapPath("/count_visit.txt")); writer.WriteLine(count_visit); writer.Close(); }
//==================================================== // // // //==================================================== static void DetectAnomalyBySrCnn(IDataView dataView, int windowSize, int backAddWindowSize, int lookaheadWindowSize, int averageingWindowSize, int judgementWindowSize, double threshold) { // Setup the estimator arguments string outputColumnName = nameof(TSPrediction.Prediction); string inputColumnName = nameof(TSData.val); //STEP 1: Create Esimtator var estimator = mlContext.Transforms.DetectAnomalyBySrCnn( outputColumnName, inputColumnName, windowSize, backAddWindowSize, lookaheadWindowSize, averageingWindowSize, judgementWindowSize, threshold); //STEP 2:The Transformed Model. ITransformer tansformedModel = estimator.Fit(CreateEmptyDataView()); //STEP 3: Use/test model //Apply data transformation to create predictions. IDataView transformedData = tansformedModel.Transform(dataView); var predictions = mlContext.Data.CreateEnumerable <TSPrediction>(transformedData, reuseRowObject: false); //Console.WriteLine("Alert\tScore\tP-Value"); System.IO.StreamWriter file = new System.IO.StreamWriter("ts-out.txt"); int count = 0; foreach (var p in predictions) { if (p.Prediction[0] == 1) { file.WriteLine(count); } count++; } file.Close(); }
/// <summary> /// 写版本配置 /// </summary> /// <param name="vc"></param> /// <returns></returns> public static void WriteVersionConfig(VersionConfig vc) { var versionFile = new System.IO.StreamWriter(PathUtil.GetFullPath(PathUtil.GetRelativePathToDataPath(PathConfig.version)), false, Encoding.UTF8); StringBuilder sb = new StringBuilder(); versionFile.WriteLine("<Config>"); versionFile.Write("\t<Version>"); versionFile.Write(vc.version.ToString()); versionFile.WriteLine("</Version>"); versionFile.WriteLine("\t<Files>"); foreach (KeyValuePair <string, VersionFileConfig> kv in vc.fileDict) { VersionFileConfig vfc = kv.Value; versionFile.WriteLine("\t\t<File>"); versionFile.Write("\t\t\t<Path>"); versionFile.Write(vfc.path.ToLower()); versionFile.WriteLine("</Path>"); versionFile.Write("\t\t\t<MD5>"); versionFile.Write(vfc.md5); versionFile.WriteLine("</MD5>"); versionFile.Write("\t\t\t<SizeByte>"); versionFile.Write(vfc.sizeByte); versionFile.WriteLine("</SizeByte>"); versionFile.WriteLine("\t\t</File>"); } versionFile.WriteLine("\t</Files>"); versionFile.WriteLine("</Config>"); versionFile.Flush(); versionFile.Close(); }
public void gameoverscr(int userpoints) { string score = @"score.txt"; string scoretxt = Path.GetFullPath(score); Console.SetCursorPosition(50, 6); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Game over!"); //if (userPoints < 0) userPoints = 0; Console.SetCursorPosition(45, 7); Console.WriteLine("Your points are: {0}", userpoints); Console.SetCursorPosition(43, 8); Console.WriteLine("Please Enter your name:"); Console.SetCursorPosition(52, 10); Console.ForegroundColor = ConsoleColor.White; string nametext = Console.ReadLine(); using (System.IO.StreamWriter file = new System.IO.StreamWriter(scoretxt, true)) { file.WriteLine(nametext + " - " + userpoints.ToString()); } Console.SetCursorPosition(36, 15); Console.WriteLine("Please press the ENTER key to exit the game."); //true here mean we won't output the key to the console, just cleaner in my opinion. Console.SetCursorPosition(40, 17); ConsoleKeyInfo keyInfo = Console.ReadKey(true); if (keyInfo.Key == ConsoleKey.Enter) { return; } }
public void WriteToStream(System.IO.StreamWriter sw, IIdentifiedSpectrum peptide) { string detailFile = this.detailDirectory + "\\" + peptide.Annotations[O18QuantificationConstants.O18_RATIO_FILE]; if (File.Exists(detailFile)) { O18QuantificationSummaryItem item = format.ReadFromFile(detailFile); var calc = item.GetCalculator(); foreach (var scan in item.ObservedEnvelopes) { if (scan.Enabled) { scan.CalculateFromProfile(item.PeptideProfile, calc); sw.Write("\t"); foreach (var func in valueFuncs) { sw.Write("\t{0}", func(scan)); } sw.WriteLine(); } } } }
static void Evaluate() { var network = (BasicNetwork)EncogDirectoryPersistence.LoadObject(Config.TrainedNetworkFile); var analyst = new EncogAnalyst(); analyst.Load(Config.AnalystFile.ToString()); var evaluationSet = EncogUtility.LoadCSV2Memory(Config.NormalizedEvaluateFile.ToString(), network.InputCount, network.OutputCount, true, CSVFormat.English, false); using (var file = new System.IO.StreamWriter(Config.ValidationResult.ToString())) { foreach (var item in evaluationSet) { var NormalizedActualoutput = (BasicMLData)network.Compute(item.Input); var Actualoutput = analyst.Script.Normalize.NormalizedFields[8].DeNormalize(NormalizedActualoutput.Data[0]); var IdealOutput = analyst.Script.Normalize.NormalizedFields[8].DeNormalize(item.Ideal[0]); //Write to File var resultLine = IdealOutput.ToString() + "," + Actualoutput.ToString(); file.WriteLine(resultLine); Console.WriteLine("Ideal : {0}, Actual : {1}", IdealOutput, Actualoutput); } } }
protected override void FinalizeData() { StringBuilder sb = new StringBuilder(); sb.Append("<rulecontrols>\r\n"); foreach (DictionaryEntry item in rulecontrollist) { string key = item.Key as string; //key = key.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """).Replace("'", "'"); RuleControl value = item.Value as RuleControl; StringBuilder record = new StringBuilder(); record.Append("<rulecontrol>\r\n"); record.Append("<rulename>" + value.rulename + "</rulename >\r\n"); record.Append("<notes>" + value.notes + "</notes >\r\n"); record.Append("<cert_tr>" + value.cert_tr + "</cert_tr >\r\n"); record.Append("<cert_impact>" + value.cert_impact + "</cert_impact >\r\n"); record.Append("<ttt_testing_results>" + value.ttt_testing_results + "</ttt_testing_results >\r\n"); record.Append("<category>" + value.category + "</category >\r\n"); record.Append("</rulecontrol>\r\n"); sb.Append(record.ToString()); } sb.Append("</rulecontrols>\r\n"); if (File.Exists(outputpath + "\rulecontrol.xml")) { File.Delete(outputpath + "\rulecontrol.xml"); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputpath + "\\rulecontrol.xml", false)) { file.WriteLine(sb.ToString()); } }
private void WriteLog(String message) { try { String fileName = DateTime.Now.Year.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Day.ToString(); if (!File.Exists(System.Threading.Thread.GetDomain().BaseDirectory + "logs\\" + DateTime.Now.Year.ToString() + "\\" + fileName + ".log")) { if (!Directory.Exists(System.Threading.Thread.GetDomain().BaseDirectory + "logs")) { Directory.CreateDirectory(System.Threading.Thread.GetDomain().BaseDirectory + "logs"); } if (!Directory.Exists(System.Threading.Thread.GetDomain().BaseDirectory + "logs\\" + DateTime.Now.Year.ToString())) { Directory.CreateDirectory(System.Threading.Thread.GetDomain().BaseDirectory + "logs\\" + DateTime.Now.Year.ToString()); } File.Create(System.Threading.Thread.GetDomain().BaseDirectory + "logs\\" + DateTime.Now.Year.ToString() + "\\" + fileName + ".log"); File.Create(System.Threading.Thread.GetDomain().BaseDirectory + "logs\\" + DateTime.Now.Year.ToString() + "\\" + fileName + ".log").Dispose(); } using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(System.Threading.Thread.GetDomain().BaseDirectory + "logs\\" + DateTime.Now.Year.ToString() + "\\" + fileName + ".log", true)) { streamWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " : " + message); } } catch (Exception e) { System.Console.WriteLine(e.Message); } }
// private async Task <DialogTurnResult> AcknowledgementStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { // Set the user's company selection to what they entered in the review-selection dialog. var userProfile = (UserProfile)stepContext.Values[UserInfo]; using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\teste\Documents\Carambola\43.complex-dialog\ResultadoArquivo.json", true)) file.WriteLine("[" + (userProfile.nomeUsuario + ",") + (userProfile.resposta1 + ",") + (userProfile.resposta2 + "]") ); // Thank them for participating. await stepContext.Context.SendActivityAsync( MessageFactory.Text($"Obrigada por sua participação, {((UserProfile)stepContext.Values[UserInfo]).nomeUsuario}!"), cancellationToken); // Exit the dialog, returning the collected user information. return(await stepContext.EndDialogAsync(stepContext.Values[UserInfo], cancellationToken)); }
static void Main(string[] args) { Deduplication deduplication = new Deduplication(); var database = deduplication.Database; string[] filePaths = Directory.GetFiles("../../../Data/"); foreach (string filePath in filePaths) { if (filePath.Contains("Paris")) { database.Load(filePath); } } //database.GenerateTiles(0.05); database.GenerateTilesByCity(); //database.AddPlace("Starbucks Coffee"); //database.AddPlace("Peets Coffee"); //database.AddPlace("Starbucks"); deduplication.Setup(); // Run the expectation maximization algorithm deduplication.ExpectationMaximization(100, 1E-3, Deduplication.Model.Name); //var cp = deduplication.IsCoreWordProbability[database.GetByName("Metro-Station Mouton Duvernet (Linie 4)")[0]]; Test test = new Test(); test.LoadGroundTruthFromFile("GroundTruth.txt"); System.IO.StreamWriter file = new System.IO.StreamWriter("precision SpatialContext.csv"); for (int i = 1; i < 15; ++i) { double precision = test.GetPrecision(deduplication.IsCoreWordProbability, i * 10); file.WriteLine(i * 10 + "," + precision); } file.Close(); }
public TextFileWriter(string path, string fileName) { bool exists = false; // sc = new StringCollection(); if (path != null) { if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } if (System.IO.File.Exists(path + "\\" + fileName + ".csv")) { exists = true; } sw = new StreamWriter(path + "\\" + fileName + ".csv", true); this.OutPath = path + "\\" + fileName + ".csv"; sw.AutoFlush = true; if (!exists) { sw.WriteLine("Year, Day, Time, Animal #, X, Y, Asleep, Behavior Mode, Energy Level, Risk, ProbFoodCap, MVL, MSL, PercptionDist, Percent Step"); } } }
public void dumpLoadCells() { try{ using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"load_dump.dmp", true)) { foreach (KeyValuePair <long, long> entry in mapping2) { try{ SimpleGraphNode simpleGraphNode = Global.CloudStorage.LoadSimpleGraphNode(entry.Key); foreach (long link in simpleGraphNode.Outlinks) { file.WriteLine(entry.Value + " " + mapping1[link]); } } catch (Exception ex) { TextWriter errorWriter = Console.Error; errorWriter.WriteLine(ex.Message); } } } } catch (Exception ex) { TextWriter errorWriter = Console.Error; errorWriter.WriteLine(ex.Message); } }
private void createFile() { StreamWriter file = new System.IO.StreamWriter(@"C:\Datos\Web\getevents.js"); DatosCehavi datos1 = new DatosCehavi(); datos1.Connect(); StringBuilder jsonData = new StringBuilder(); //file.WriteLine("var curEvents = "); DateTime CurTime = DateTime.Now; DateTime EndTime = CurTime.AddMonths(1); string json = datos1.getJsonEvents(CurTime, EndTime, "IdEvento in (select Id from Terapias where IdTerapeuta=" + this.curTerapeuta.ToString() + ") or IdEvento in (select Id from Citas where IdTerapeuta=" + this.curTerapeuta.ToString() + ")"); if (json.Length != 0) { jsonData.Append("var curEvents = "); jsonData.Append(json); jsonData.Append(";"); } else { jsonData.Append("var curEvent = [];"); } file.WriteLine(jsonData.ToString()); file.Close(); }
static void Main(string[] args) { Helper h = new Helper(); string path = ""; if (args == null || args.Length == 0) { path = Directory.GetCurrentDirectory(); } else { path = args[0]; } ObservableCollection <ArtifactCount> result = new ObservableCollection <ArtifactCount>(); h.CountArtifactsByTypeBatch(path, result); // Write the string to a file. System.IO.StreamWriter file = new System.IO.StreamWriter(path + "\\summary.csv"); foreach (ArtifactCount item in result) { file.WriteLine("\"" + item.ArtifcatType + "\", " + item.Count); } file.Close(); }
/// <summary> /// 在文件末尾添加 /// </summary> /// <param name="?"></param> public void AddFile(string filepath, string str) { try { //lock (txtLock) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filepath, true, System.Text.Encoding.Default)) { sw.BaseStream.Seek(0, System.IO.SeekOrigin.End); sw.WriteLine(str); sw.Flush(); sw.Close(); } } } catch (Exception e) { try { string error = _logPath + "/error.txt"; if (!System.IO.File.Exists(error)) { FileStream fs = File.Create(error); fs.Close(); } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(error, true, System.Text.Encoding.Default)) { sw.BaseStream.Seek(0, System.IO.SeekOrigin.End); sw.WriteLine(str + "\r\n" + e.Message + "\r\n"); sw.Flush(); sw.Close(); } } catch { } } }
public void ProcessFile(string path) { string[] filesplit = path.Split('\\'); string file = filesplit[filesplit.Length - 1]; foreach (string term in terms) { if (file.ToLower().Contains(term.ToLower())) { lock (_ListLock) { _FilesFound.Add(path); using (System.IO.StreamWriter outFile = new System.IO.StreamWriter(_OutputFile, true)) { outFile.WriteLine(path); } } break; } } }
public static void WriteListToFile(List <string> listToWrite, bool overwriteExistingContent, string filePath) { try { //Overwrite existing contents if true if (overwriteExistingContent == true) { File.WriteAllText(filePath, ""); } //Write items from list foreach (var item in listToWrite) { using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, true)) { file.WriteLine(item); } } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } }
private static void printInFile(string output, string fileNameLoc, bool printConsole = true) { try { using (System.IO.StreamWriter file = new System.IO.StreamWriter(fileNameLoc, true)) { if (printConsole) { Console.WriteLine(output); } file.WriteLine(output); } } catch (ObjectDisposedException) { string error = "Pisanje v datoteko exc: ObjectDisposedException."; Console.WriteLine(error); } catch (IndexOutOfRangeException) { string error = "Pisanje v datoteko exc: IndexOutOfRangeException."; Console.WriteLine(error); } }
protected static void WriteLog(string type, string className, string content) { if (!System.IO.Directory.Exists(Log.path)) { System.IO.Directory.CreateDirectory(Log.path); } string text = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"); string text2 = Log.path + "/" + System.DateTime.Now.ToString("yyyy-MM-dd") + ".log"; System.IO.StreamWriter streamWriter = System.IO.File.AppendText(text2); string value = string.Concat(new string[] { text, " ", type, " ", className, ": ", content }); streamWriter.WriteLine(value); streamWriter.Close(); }
internal void WriteErrorLog(String message) { Debug.WriteLine(message); StreamWriter sw = null; string path = AppDomain.CurrentDomain.BaseDirectory; try { DateTime dateTime = DateTime.Now; String filename = String.Format("{0}_{1}_{2}_BioData_Update_ServiceLog.txt", dateTime.Year.ToString(), dateTime.Month.ToString(), dateTime.Day.ToString()); String fullpath = System.IO.Path.Combine(path, filename); lock (LogWriter.obj) { using (System.IO.FileStream stream = System.IO.File.Open(fullpath, System.IO.FileMode.Append)) { sw = new System.IO.StreamWriter(stream); sw.AutoFlush = true; sw.WriteLine(DateTime.Now.ToString() + " : " + message); sw.Close(); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } }
static void Main(string[] args) { //Declaration Variable int count = 0; string originalText, text2, pathFile = @"C:\Users\Mi PC\workspaceFP\FunctionalSynopsisCSharp\FunctionalSynopsisCSharp\Prueba\SynopsisFile.txt"; char[] vocals = { 'a', 'e', 'i', 'o', 'u' }; //Create, write or overwrite the File using (System.IO.StreamWriter file = new System.IO.StreamWriter(pathFile, false)) { file.WriteLine("This is a default message -> C# IS LOVE"); } //Read the File and Count the vocals originalText = System.IO.File.ReadAllText(pathFile); text2 = originalText.ToLower(); count = text2.Count(x => vocals.Contains(x)); Console.WriteLine("THE FILE WAS CREATED\n"); Console.WriteLine(originalText); Console.WriteLine("VOCALS -> {0}\n", count); /*Delete the File * if (File.Exists(pathFile)) * { * File.Delete(pathFile); * Console.WriteLine("FILE WAS DELETED..."); * } */ Console.WriteLine("PLEASE PRESS ANY KEY TO EXIT..."); Console.ReadKey(); }
private bool saveConfig() { // TODO: handle existing file using (System.IO.StreamWriter file = new System.IO.StreamWriter(ClientServerConnection.ConfigFile, false)) { file.WriteLine("[settings]"); file.WriteLine(ClientServerConnection.CONFIG_SERVER + "=" + account.ServerName); file.WriteLine(ClientServerConnection.CONFIG_PORT + "=" + account.ServerPort.ToString()); file.WriteLine(ClientServerConnection.CONFIG_USER + "=" + account.User); // file.WriteLine("salt=" + account.Salt); file.WriteLine(ClientServerConnection.CONFIG_PASSWORD + "=" + account.Password); file.WriteLine(ClientServerConnection.CONFIG_DIR + "=" + account.Directory); Console.WriteLine("pass: "******"Config file written: " + ClientServerConnection.ConfigFile); return(true); }
//public static int Mesh_SingleRim(ref WEntity2D[] Rim, ref WMesh2D_Para MP, string Name) //{ // WShapeRim2D Shape = Rim_Output(ref Rim, MP.Path, Name); // if (Shape == null) return -1; // Poly_SingleRim(Shape.Count, MP.Path, Name); // WMesh2D_Mesh Mesh = Mesh2D_TriangleMesh.Triangle_Mesh(ref MP, Name); /////调用 // if (Mesh == null) return -1; // return Shape.Count; //} private static void Poly_SingleRim(int Q, string Path, string Name) { StreamWriter Sw = new System.IO.StreamWriter(Path + Name + ".poly"); StreamReader Sr; Sw.WriteLine(Convert.ToString(Q) + " 2 1 1"); String t; string[] t_1; Sr = new System.IO.StreamReader(Path + Name + ".rim"); int N = 0; String Num; while (Sr.Peek() != -1) { t_1 = Sr.ReadLine().Split(' '); Num = t_1[0]; t_1 = t_1[1].Split(','); N++; t = Convert.ToString(N) + " " + t_1[0] + " " + t_1[1] + " 0 " + Num; Sw.WriteLine(t); } Sr.Close(); Sr.Dispose(); //////////////////////////////////////////////////////////////// Sw.WriteLine(Convert.ToString(Q) + " 1"); for (int i = 1; i < Q; i++) { t = Convert.ToString(i) + " " + Convert.ToString(i) + " " + Convert.ToString(i + 1) + " 0"; Sw.WriteLine(t); } t = Convert.ToString(Q) + " " + Convert.ToString(1) + " " + Convert.ToString(Q) + " 0"; Sw.WriteLine(t); Sw.WriteLine("0"); Sw.Close(); Sw.Dispose(); System.IO.File.Delete(Path + Name + ".rim"); }
static void Main(string[] args) { try { String vernum = ""; XmlDocument _xmldoc; XmlNodeList _xmlnode; _xmldoc = new XmlDocument(); _xmldoc.Load("Installation.xml"); _xmlnode = _xmldoc.GetElementsByTagName("Config"); String subversion = ""; if ((args != null) && (args.Length > 0)) { subversion = args[0] + "."; Console.WriteLine("Subversion: " + subversion); } // Name String name = _xmlnode[0].ChildNodes.Item(0).InnerText.Trim(); Console.WriteLine("Name: " + name); // ExeVersion String exeversion = _xmlnode[0].ChildNodes.Item(1).InnerText.Trim(); Console.WriteLine("ExeVersion: " + exeversion); if (exeversion != "") { vernum = System.Reflection.AssemblyName.GetAssemblyName(exeversion).Version.ToString(); Console.WriteLine("==> Version number: " + vernum); } // Version String version = _xmlnode[0].ChildNodes.Item(2).InnerText.Trim(); Console.WriteLine("Version: " + version); if (version != "") { vernum = version; Console.WriteLine("==> Version number: " + vernum); } // Create destination dir String destination = ""; //if (subversion == "") destination = vernum + "." + name; //else // destination = vernum + "." + subversion + name ; if (Directory.Exists(destination)) { Console.WriteLine("Destination directory " + destination + " exists, remove old one"); DeleteDirectory(destination, true); } Console.WriteLine("Create destination directory " + destination); Directory.CreateDirectory(destination); // DirToCopy XmlNode dirs = _xmlnode[0].ChildNodes.Item(3); foreach (XmlNode elt in dirs.ChildNodes) { String src = elt.Attributes[0].InnerText.Trim(); String dst = elt.Attributes[1].InnerText.Trim(); if (dst == "") { dst = destination; } else { dst = destination + "/" + dst; } Console.WriteLine("DirToCopy - src: " + src + ", dst: " + dst); CopyAll(new DirectoryInfo(src), new DirectoryInfo(dst)); } // FileToCopy XmlNode files = _xmlnode[0].ChildNodes.Item(4); foreach (XmlNode elt in files.ChildNodes) { String src = elt.Attributes[0].InnerText.Trim(); String dst = elt.Attributes[1].InnerText.Trim(); if (dst == "") { dst = destination; } else { dst = destination + "/" + dst; } Console.WriteLine("FileToCopy - src: " + src + ", dst: " + dst); /* * try * { * if (File.Exists(dst)) * { * Console.WriteLine("*** delete " + dst); * File.Delete(dst); * Console.WriteLine("*** done!"); * } * else * Console.WriteLine("*** not existing " + dst); * } * catch (Exception ex) * { * Console.WriteLine(ex.Message); * } */ File.Copy(src, dst, true); } // Une commande avant la fin ? Console.WriteLine("One last command?"); XmlNode eltexe = _xmlnode[0].ChildNodes.Item(5); String execmd = eltexe.Attributes[0].InnerText; String exeparams = eltexe.Attributes[1].InnerText; Console.WriteLine("Last command before the end: " + execmd + " " + exeparams); if (execmd != "") { String[] ps = exeparams.Split(';'); foreach (String p in ps) { if ((p != null) && (p != "")) { // On se place dans le répertoire de destination //String before = Path.GetDirectoryName(Application.ExecutablePath); String before = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(destination); Console.WriteLine("--> Last command before the end: " + execmd + " " + p); var process = System.Diagnostics.Process.Start(execmd, p); process.WaitForExit(); Directory.SetCurrentDirectory(before); } } } // Version minimale pour forcer l'update String versionup = _xmlnode[0].ChildNodes.Item(6).InnerText.Trim(); Console.WriteLine("VersionMinForUpdate: " + versionup); if (versionup != "") { Console.WriteLine("==> Version number for update: " + versionup); } // Zip it? try { String szip = _xmlnode[0].ChildNodes.Item(7).InnerText.Trim(); Console.WriteLine("Zip: " + szip); if (szip == "True") { String zipname = vernum + "." + subversion + name; String zipfile = zipname + ".zip"; if (File.Exists(zipfile)) { File.Delete(zipfile); } ZipFile.CreateFromDirectory(destination, zipfile, CompressionLevel.Optimal, true); // La même chose avec un mot de passe ? /* * if (_xmlnode[0].ChildNodes.Count >= 9) * { * String szipassword = _xmlnode[0].ChildNodes.Item(8).InnerText.Trim(); * Console.WriteLine("Zip password: "******"images" directory in the zip archive * zip.AddDirectory(destination, destination); * * // Le zip password * zip.Save(zipname + ".password.zip"); * } * } */ } } catch (Exception ex) { Console.WriteLine(ex.Message); } // Write version.ver System.IO.StreamWriter ver = new System.IO.StreamWriter("version.ver", false); if (versionup == "") { ver.WriteLine(vernum + "#"); } else { ver.WriteLine(vernum + "#MINVER_" + versionup); } ver.Close(); } catch (Exception excp) { Console.WriteLine(excp.Message); } }
public static int GenerarInstalador(int idVersion, string fileVersion, string dirSource, string dirN1, string dirFuentes) { try { var version = GetVersiones(null).SingleOrDefault(x => x.IdVersion == idVersion); using (System.IO.StreamWriter file = new System.IO.StreamWriter(dirSource + fileVersion + ".iss", false, Encoding.GetEncoding("ISO-8859-1"))) { file.WriteLine("#define MyAppName \"WinPer\""); file.WriteLine("#define MyAppVersion \"" + version.Release + "\""); file.WriteLine("#define MyAppPublisher \"INNOVASOFT.\""); file.WriteLine("#define MyAppURL \"http://www.innovasoft.cl\""); file.WriteLine("#define MyOutputDir \"" + dirSource + "Output\""); file.WriteLine("#define MyOutputBaseFilename \"" + fileVersion + "\""); file.WriteLine(@""); file.WriteLine(@"[Setup]"); file.WriteLine(@"AppId={{" + idVersion + "}}"); file.WriteLine(@"AppName={#MyAppName}"); file.WriteLine(@"AppVersion={#MyAppVersion}"); file.WriteLine(@"AppPublisher={#MyAppPublisher}"); file.WriteLine(@"AppPublisherURL={#MyAppURL}"); file.WriteLine(@"AppSupportURL={#MyAppURL}"); file.WriteLine(@"AppUpdatesURL={#MyAppURL}"); file.WriteLine(@"DefaultDirName={localappdata}\WinperSetupUI\{#MyAppVersion}"); file.WriteLine(@"DisableDirPage=yes"); file.WriteLine(@"DefaultGroupName={#MyAppName}"); file.WriteLine(@"DisableProgramGroupPage=yes"); file.WriteLine(@"OutputDir={#MyOutputDir}"); file.WriteLine(@"OutputBaseFilename={#MyOutputBaseFilename}"); file.WriteLine(@"Compression=lzma"); file.WriteLine(@"SolidCompression=yes"); file.WriteLine(@""); file.WriteLine(@"[Languages]"); file.WriteLine("Name: \"spanish\"; MessagesFile: \"compiler:Languages\\Spanish.isl\""); file.WriteLine(@""); file.WriteLine(@"[Files]"); foreach (var componente in version.Componentes) { if (componente.Extension.Equals(".sql", StringComparison.OrdinalIgnoreCase)) { file.WriteLine(string.Format("Source: \"{0}\"; DestDir: \"{{app}}\"", dirSource + "\\Scripts\\" + componente.Name)); } else { file.WriteLine(string.Format("Source: \"{0}\"; DestDir: \"{{app}}\"", dirSource + componente.Name)); } } if (!version.IsVersionInicial) { var modsVersion = ProcessMsg.Version.GetModulosVersiones(idVersion, null); var mods = ProcessMsg.Modulo.GetModulos(null).Where(x => modsVersion.Exists(y => y.Equals(x.NomModulo, StringComparison.OrdinalIgnoreCase))).ToList(); var compMod = ProcessMsg.ComponenteModulo.GetComponentesModulos().Where(x => mods.Exists(y => y.idModulo == x.Modulo) && x.TipoComponentes.isCompCambios).ToList(); foreach (var txt in compMod) { file.WriteLine(string.Format("Source: \"{0}\"; DestDir: \"{{app}}\"", Path.Combine(dirN1, mods.SingleOrDefault(x => x.idModulo == txt.Modulo).Directorio, txt.Nombre))); } } if (version.HasDeploy31) { file.WriteLine(string.Format("Source: \"{0}\"; DestDir: \"{{app}}\"", Path.Combine(dirFuentes, "Utils", "Deploy31.exe"))); } file.WriteLine(@""); file.WriteLine(@"[Icons]"); file.WriteLine(@"Name: ""{group}\WinPer""; Filename: ""{app}\reconect.exe"""); file.WriteLine(@""); file.WriteLine(@"[Dirs]"); file.WriteLine(@"Name: ""{app}\info"""); file.WriteLine(@"Name: ""{app}\plantillas_certificados"""); file.WriteLine(@"Name: ""{app}\plantillas_contratos"""); file.WriteLine(@"Name: ""{app}\plantillas_finiquitos"""); file.WriteLine(@"Name: ""{app}\plantillas_papeletas_rem"""); file.WriteLine(@""); file.WriteLine(@"[Registry]"); //file.WriteLine(@"Root: HKCU; Subkey: ""SOFTWARE\WinperUpdate""; ValueType: string; ValueName: ""Version""; ValueData: """ + version.Release + "\""); file.WriteLine(@"Root: HKCU; Subkey: ""SOFTWARE\WinperUpdate""; ValueType: string; ValueName: ""Status""; ValueData: """ + "begin" + "\""); file.Close(); } return(1); } catch (Exception ex) { var msg = "Excepcion Controlada: " + ex.Message; throw new Exception(msg, ex); } }