/// <summary> /// Writes the rows of a datatable ot a csv file /// </summary> /// <param name="queue"></param> /// <param name="csvWriter"></param> /// <param name="maxSize"> /// The maximum size of the current part in bytes. NOTE: this is a lower bound, and a single line may flow over this limit. /// We have seen log lines of up to 5Mb in length, so using 15 here should almost guarantee us a request size of under 20Mb. /// </param> /// <returns>The index of the last written row, or -1 if the whole table has been written out</returns> public static int WriteCSVBody(DataTable queue, CsvHelper.CsvWriter csvWriter, int startRowIdx, long maxSize) { var columnCount = queue.Columns.Count; var byteCount = 0; // the maximum row index we are willing to touch var maxRowIdx = queue.Rows.Count; // Do an indexed for loop, so we can return the row index for (var rowIdx = startRowIdx; rowIdx < maxRowIdx; rowIdx++) { // try to write the row out try { // update the byte count at the end of the row write so that if any exceptions happen, the bytescount // wont contain the bytes of the not written lines byteCount += WriteCsvLine(csvWriter, columnCount, queue.Rows[rowIdx]); // compare the current byte count with the maximum and stop after this line if we are over // and as we have already written one more file let's just return rowIndex plus 1 instead of rowIndex // otherwise we could end up with an infinite loop when there is a row that is bigger than our max file size if (byteCount > maxSize) { return(rowIdx + 1); } } catch (CsvWriterException ex) { Log.Error(ex, "Error writing record to CSV."); // if we didnt write this line out then we dont increment the row byte count } } // we return -1 indicating that the whole table has been written return(-1); }
public string GetAsCSV() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); var m = new StringWriter(sb); TextWriter tw = m; var config = new CsvConfiguration(CultureInfo.CurrentCulture); config.Delimiter = ColumnDelimiter; var p = new CsvHelper.CsvWriter(tw, config); //CSVLine Line; foreach (var line in Lines) { foreach (var c in line.Columns) { p.WriteField(c); } p.NextRecord(); } p.Flush(); return(sb.ToString()); }
public ActionResult DownloadCareManagers() { using (var writer = new System.IO.StreamWriter(Response.OutputStream, Encoding.GetEncoding("Shift-JIS"))) using (var csv = new CsvHelper.CsvWriter(writer)) { csv.WriteField("事業所ID"); csv.WriteField("ケアマネID"); csv.WriteField("氏名"); csv.WriteField("登録者メールアドレス"); csv.WriteField("生年月日"); csv.WriteField("性別"); csv.WriteField("資格取得年月日"); csv.NextRecord(); foreach (var m in db.CareManagers.Where(m => m.UserId != null && m.Email != null).Include(m => m.CareHome).Include(m => m.User)) { csv.WriteField(m.CareHome.CareHomeCode); csv.WriteField(m.CareManagerId); csv.WriteField(m.Name); csv.WriteField(m.Email); csv.WriteField(m.Birthday); csv.WriteField(m.Gender); csv.WriteField(m.Licensed); //csv.WriteField(m.Licenses); csv.NextRecord(); } } Response.ContentType = "text/csv"; Log(LogType.Admin, "CSVでケアマネ一覧をダウンロードしました。"); return(null); }
bool ExportPrices(Message message) { try { string fileName = $"C:\\temp\\price_{DateTime.Now.ToString("ddMMyyyyhh")}.csv"; using (var sw = new StreamWriter(fileName, File.Exists(fileName))) { var writer = new CsvHelper.CsvWriter(sw, _csvConfig); var result = JsonConvert.DeserializeObject <PDLPRCP>(Encoding.UTF8.GetString(message.Body)); writer.WriteField(result.StyleNumber); writer.WriteField(result.ColourCode); writer.WriteField(result.SizeCode); writer.WriteField(result.CountryCode); writer.WriteField(result.BaseCcyCurrentRet); writer.WriteField(result.BaseCcyOriginalRet); writer.NextRecord(); } //if (!File.Exists(fileName)) //{ // using (var sw = new StreamWriter(fileName)) // { // var writer = new CsvHelper.CsvWriter(sw, _csvConfig); // var result = JsonConvert.DeserializeObject<PDLPRCP>(Encoding.UTF8.GetString(message.Body)); // writer.WriteField(result.StyleNumber); // writer.WriteField(result.ColourCode); // writer.WriteField(result.SizeCode); // writer.WriteField(result.CountryCode); // writer.WriteField(result.BaseCcyCurrentRet); // writer.WriteField(result.BaseCcyOriginalRet); // writer.NextRecord(); // } //} //else //{ // using (var sw = new StreamWriter(fileName,true)) // { // var writer = new CsvHelper.CsvWriter(sw, _csvConfig); // writer.NextRecord(); // var result = JsonConvert.DeserializeObject<PDLPRCP>(Encoding.UTF8.GetString(message.Body)); // writer.WriteField(result.StyleNumber); // writer.WriteField(result.ColourCode); // writer.WriteField(result.SizeCode); // writer.WriteField(result.CountryCode); // writer.WriteField(result.BaseCcyCurrentRet); // writer.WriteField(result.BaseCcyOriginalRet); // writer.NextRecord(); // } //} return(true); } catch (Exception ex) { log.Error("Export prices: ", ex); } return(false); }
/// <summary> /// Write database records to text based file format. /// </summary> /// <param name="path">The fields file path.</param> /// <param name="fs">The file system.</param> /// <param name="database">The source records database.</param> void ITextFieldWriter <XDatabase> .Write(string path, IFileSystem fs, XDatabase database) { using (var writer = new System.IO.StringWriter()) { var configuration = new CSV.Configuration.CsvConfiguration(); configuration.Delimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator; configuration.CultureInfo = CultureInfo.CurrentCulture; using (var csv = new CSV.CsvWriter(writer, configuration)) { // columns csv.WriteField(database.IdColumnName); foreach (var column in database.Columns) { csv.WriteField(column.Name); } csv.NextRecord(); // records foreach (var record in database.Records) { csv.WriteField(record.Id.ToString()); foreach (var value in record.Values) { csv.WriteField(value.Content); } csv.NextRecord(); } } fs.WriteUtf8Text(path, writer.ToString()); } }
public static void exportMappingSet(MappingSet mappingSet, string filePath) { if (mappingSet != null) { using (TextWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8)) { var csv = new CSV.CsvWriter(writer); csv.Configuration.RegisterClassMap <CSVMappingRecordMap>(); csv.Configuration.Delimiter = ";"; var csvMappingRecords = new List <CSVMappingRecord>(); //create the CSV mapping records foreach (var mapping in mappingSet.mappings) { //create the record var mappingRecord = new CSVMappingRecord(); mappingRecord.sourcePath = ((MappingNode)mapping.source).getMappingPathExportString(); mappingRecord.targetPath = ((MappingNode)mapping.target).getMappingPathExportString(); mappingRecord.mappingLogic = createMappingLogicString(mapping); //add the record to the list csvMappingRecords.Add(mappingRecord); } //write the CSV mapping records to the filename csv.WriteRecords(csvMappingRecords); } } }
protected override void DoPostWorkCompleted() { // write the item feed status into the CSV file var resultFilePath = string.Format("{0}\\eBayProductsEndItemResults{1}.csv", _resultFileDirecctory, _systemJob.Id); // write into the file using (var streamWriter = new StreamWriter(resultFilePath)) { var writer = new CsvHelper.CsvWriter(streamWriter); // write the column headers writer.WriteField("EisSKU"); writer.WriteField("ItemId"); writer.WriteField("Status"); writer.WriteField("Message"); writer.NextRecord(); foreach (var item in _itemFeeds) { writer.WriteField(item.EisSKU); writer.WriteField(item.ItemId); writer.WriteField(item.Status); writer.WriteField(item.Message); // move to the next row writer.NextRecord(); } } // update the system job parameters out for the file path of the result file _jobRepository.UpdateSystemJobParametersOut(_systemJob.Id, resultFilePath); }
/// <summary> /// /// </summary> /// <param name="bindings"></param> private static void OutputToFile(List <Binding> bindings) { using (FileStream fileStream = new FileStream(Path.Combine(fclp.Object.Output, "wmi-parser.tsv"), FileMode.Create, FileAccess.Write)) using (StreamWriter streamWriter = new StreamWriter(fileStream)) using (CsvWriter cw = new CsvHelper.CsvWriter(streamWriter)) { cw.Configuration.Delimiter = "\t"; // Write out the file headers cw.WriteField("Name"); cw.WriteField("Type"); cw.WriteField("Arguments"); cw.WriteField("Filter Name"); cw.WriteField("Filter Query"); cw.NextRecord(); foreach (var b in bindings) { cw.WriteField(b.Name); cw.WriteField(b.Type); cw.WriteField(b.Arguments); cw.WriteField(b.Filter); cw.WriteField(b.Query); cw.NextRecord();; } } }
/// <summary> /// Writes a csv header from a datatable /// </summary> /// <param name="queue"></param> /// <param name="csvWriter"></param> public static void WriteCSVHeader(DataTable queue, CsvHelper.CsvWriter csvWriter) { foreach (DataColumn column in queue.Columns) { csvWriter.WriteField(column.ColumnName); } csvWriter.NextRecord(); }
public static void WriteStats(List <IterationStats> stats, string path) { using (var writer = new System.IO.StreamWriter(path)) using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.InvariantCulture)) { csv.WriteRecords(stats); } }
public static DataWriter <T> Create(string path) { var streamWriter = new StreamWriter(path); var csvWriter = new CsvHelper.CsvWriter(streamWriter); csvWriter.WriteHeader <T>(); csvWriter.NextRecord(); return(new DataWriter <T>(csvWriter)); }
public Task <object> Evaluate(IEnumerable <object> objects) { using (var writer = new StringWriter()) using (var csv = new CsvHelper.CsvWriter(writer, csvConfig)) { csv.WriteRecords(objects); return(Task.FromResult <object>(writer.ToString())); } }
public void WriteOutputFile <T>(IEnumerable <T> records, string outputFile) { using (var fileWritter = File.CreateText(outputFile)) { CsvHelper.CsvWriter w = new CsvHelper.CsvWriter(fileWritter); w.WriteHeader <T>(); w.WriteRecords(records); } }
/// <summary> /// Creates CSV-file to given path using Exportmodel as configurations and measurementModels as data. /// </summary> /// <param name="fullPath"></param> /// <param name="options"></param> /// <param name="measurements"></param> public void CreateCsvFile(string filename, string directoryPath, ExportModel options, List <MeasurementModel> measurements) { _measurements = measurements; try { if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } using (TextWriter tw = new StreamWriter(directoryPath + filename)) { using (var writer = new CsvHelper.CsvWriter(tw)) { if (!string.IsNullOrEmpty(options.ColumnDelimeter)) { writer.Configuration.Delimiter = options.ColumnDelimeter; } writer.Configuration.HasHeaderRecord = options.ShowHeaders; var selected = CreateSelectedValueList(options); if (options.ShowHeaders) { var headers = CreateHeaders(measurements, selected); foreach (var h in headers) { writer.WriteField(h); } writer.NextRecord(); } var functions = CreateDataValueFunctions(selected); for (mIndex = 0; mIndex < measurements.Count; mIndex++) { writer.WriteField(measurements[mIndex].Object); writer.WriteField(measurements[mIndex].Tag); writer.WriteField(measurements[mIndex].Timestamp.ToString(options.Datetimeformat)); writer.WriteField(measurements[mIndex] != null ? measurements[mIndex].Location?.ToString() : ""); writer.WriteField(measurements[mIndex].Note); for (dIndex = 0; dIndex < measurements[mIndex].Data.Count; dIndex++) { foreach (var f in functions) { var result = f.Invoke(); writer.WriteField((object)result ?? (object)string.Empty); } } writer.NextRecord(); } } } } catch (Exception) { throw; } }
/// <summary> /// Gets message object to be returned by the service as the result of the operation /// </summary> /// <returns></returns> public Task ExecuteResultAsync(ActionContext context) { HttpResponseMessage result = new HttpResponseMessage(); switch (this.OutputFormat) { case OutputFormat.ApplicationXmlExternalParsedEntity: case OutputFormat.TextXmlExternalParsedEntity: case OutputFormat.ApplicationXml: case OutputFormat.TextXml: case OutputFormat.ApplicationXmlWaterMl2: { result.Content = new XmlContent(this.ResultObject, this.OutputFormat.ToStringValue()); result.RequestMessage = new HttpRequestMessage(new HttpMethod(_request.Method), Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(_request)); break; } case OutputFormat.TextCsv: { if (this.ResultObject is IEnumerable <object> ) { using (var memoryStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memoryStream)) using (var csvWriter = new CsvHelper.CsvWriter(streamWriter, CultureInfo.InvariantCulture)) { var records = this.ResultObject as IEnumerable <object>; csvWriter.WriteRecords(records); streamWriter.Flush(); memoryStream.Position = 0; result.Content = new StreamContent(memoryStream); result.RequestMessage = new HttpRequestMessage(new HttpMethod(_request.Method), Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(_request)); //result.ContentType = new MediaTypeHeaderValue("text/csv").MediaType; } } else { throw new NoApplicableCodeException("Message is empty or not set or result object is not supported."); } break; } case OutputFormat.TextPlain: { string message = string.Format(CultureInfo.InvariantCulture, "{0}", this.ResultObject); if (string.IsNullOrEmpty(message)) { throw new NoApplicableCodeException("Message is empty or not set or result object is not supported."); } result.Content = new StringContent(message); break; } default: break; } return(Task.FromResult(result));; }
private static void SaveToCsv() { var metsRecords = LoadDataRecords(TRAINING_DATA_FILE, 0); using (var tw = File.CreateText($"d:\\training_data.csv")) { var csv = new CsvHelper.CsvWriter(tw); csv.WriteHeader<MetsDataRecord>(); csv.NextRecord(); csv.WriteRecords(metsRecords); } }
public static void WriteAddressBookCsv(AddressBook addressBook) { string path = @"C:\Users\prajv\source\repos\AddressBookDay13\AddressBook.csv"; using (StreamWriter writer = new StreamWriter(path)) { var csv = new CsvHelper.CsvWriter(writer, CultureInfo.InvariantCulture); csv.Configuration.MemberTypes = CsvHelper.Configuration.MemberTypes.Fields; csv.WriteRecords(AddressBook.Records); writer.Close(); } }
public static void SaveList(List <List> _list) { var path = @"list.csv"; using (TextWriter fileWriter = new StreamWriter(path, false)) using (var csv = new CsvHelper.CsvWriter(fileWriter, System.Globalization.CultureInfo.InvariantCulture)) { csv.Configuration.HasHeaderRecord = true; csv.Configuration.RegisterClassMap <ListMapper>(); csv.WriteRecords(_list); } }
private void SaveSupplierBacsExport(SupplierBacsExport supplierBacsExport) { var fileName = string.Format("{0}_BACSExport.csv", BacsExportType.Supplier); using (var writer = new StreamWriter(new FileStream(fileName, FileMode.Create))) { using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture)) { csv.WriteRecords(supplierBacsExport.SupplierPayment); } } }
private void SavePayments(IEnumerable <BacsResult> payments, BacsExportType type) { var filename = string.Format("{0}_BACSExport.csv", type); using (var writer = new StreamWriter(new FileStream(filename, FileMode.Create))) { using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture)) { csv.WriteRecords(payments); } } }
static void Main(string[] args) { var p = new FluentCommandLineParser<ApplicationArguments>(); // specify which property the value will be assigned too. p.Setup(arg => arg.Directory) .As('d', "directory").WithDescription("Directory to process") .Required(); p.Setup(arg => arg.CSVFile) .As('f', "file") .WithDescription("CSV File name"); p.Setup(arg => arg.Log) .As('l', "log") .WithDescription("Log output") .SetDefault(false); // use the standard fluent Api to define a default value if non is specified in the arguments p.SetupHelp("h", "?", "help") .Callback(s => Console.WriteLine(s)); var result = p.Parse(args); if(result.HelpCalled) return; if(result.HasErrors == false) { //C:\Users\10063026\Desktop\BDS-MCTGCTV ApplicationArguments options = (ApplicationArguments)p.Object; var results = ProcessDirectory(options.Directory); Console.WriteLine(results.Count+" UAFs processed"); if (options.CSVFile != null) { TextWriter file = new StreamWriter(options.CSVFile); var csv = new CsvHelper.CsvWriter(file); csv.WriteRecords(results); file.Flush(); } else { CsvWriter csv = new CsvHelper.CsvWriter(Console.Out); csv.WriteRecords(results); } } else { Console.WriteLine(result.ErrorText); } }
public static void WriteCollectionToCsv(IEnumerable records, Type classtype, string filename) { using (var sw = new StreamWriter(filename)) { var csvHelper = new CsvHelper.CsvWriter(sw); csvHelper.WriteHeader(classtype); csvHelper.NextRecord(); csvHelper.WriteRecords(records); sw.Flush(); csvHelper.Flush(); } }
public static string CreateCSV(IEnumerable <StringTableEntry> entries) { using (var textWriter = new System.IO.StringWriter()) { // Generate the localised .csv file // Use the invariant culture when writing the CSV var csv = new CsvHelper.CsvWriter( textWriter, // write into this stream GetConfiguration() // use this configuration ); var fieldNames = new[] { "language", "id", "text", "file", "node", "lineNumber", "lock", "comment", }; foreach (var field in fieldNames) { csv.WriteField(field); } csv.NextRecord(); foreach (var entry in entries) { var values = new[] { entry.Language, entry.ID, entry.Text, entry.File, entry.Node, entry.LineNumber, entry.Lock, entry.Comment, }; foreach (var value in values) { csv.WriteField(value); } csv.NextRecord(); } return(textWriter.ToString()); } }
public static void WriteObjectToCsv(Metrics metrics, Type classtype, string filename) { using (var sw = new StreamWriter(filename)) { var csvHelper = new CsvHelper.CsvWriter(sw); csvHelper.WriteHeader(classtype); csvHelper.NextRecord(); csvHelper.WriteField(metrics.Distance); csvHelper.WriteField(metrics.Number); sw.Flush(); csvHelper.Flush(); } }
public static void WriteEndPosition(Dictionary <CellCoords, Cell> writeDictionary, string path) { List <PredefinedPosition> endPositions = new List <PredefinedPosition>(); foreach (KeyValuePair <CellCoords, Cell> cellEntry in writeDictionary) { endPositions.Add(new PredefinedPosition(cellEntry.Key.x, cellEntry.Key.y)); } using (var writer = new System.IO.StreamWriter(path)) using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.InvariantCulture)) { csv.WriteRecords(endPositions); } }
/// <summary> /// Prepares the response output to be done as a CSV file, returning a wrapper that serialized the data /// that should be returned to let the process finalize (as of a Get, Post, Put, Delete methods). /// </summary> /// <param name="data"></param> /// <param name="downloadWithFilename">If given, force browser to download the content with the given file name</param> /// <returns></returns> public CsvHelper.CsvWriter ExportAsCsv(IEnumerable <object> data, string downloadWithFilename = null) { if (!String.IsNullOrEmpty(downloadWithFilename)) { WebPage.Response.AddHeader("Content-Disposition", "attachment; filename=" + downloadWithFilename); } var csv = new CsvHelper.CsvWriter(WebPage.Response.Output); csv.Configuration.MemberTypes = CsvHelper.Configuration.MemberTypes.Fields | CsvHelper.Configuration.MemberTypes.Properties; csv.WriteRecords(data); return(csv); }
public void EscreverArquivoCSV(string local, List <Estudante> estudantes) { using (StreamWriter sw = new StreamWriter(local, false, new UTF8Encoding(true))) { using (CsvWriter csvWriter = new CsvHelper.CsvWriter(sw, System.Globalization.CultureInfo.InvariantCulture)) { csvWriter.WriteHeader <Estudante>(); csvWriter.NextRecord(); foreach (Estudante est in estudantes) { csvWriter.WriteRecord <Estudante>(est); csvWriter.NextRecord(); } } } }
public static T Write <T>(Func <MemoryStream, StreamReader, StreamWriter, CsvHelper.CsvWriter, T> write) { var config = new CsvConfiguration(CultureInfo.CurrentCulture) { InjectionCharacters = InjectionCharacters, SanitizeForInjection = true }; using (var memoryStream = new MemoryStream()) using (var streamReader = new StreamReader(memoryStream)) using (var streamWriter = new StreamWriter(memoryStream)) using (var csvWriter = new CsvHelper.CsvWriter(streamWriter, config)) { csvWriter.Configuration.TypeConverterCache.AddConverter <string>(new CustomConverter()); return(write(memoryStream, streamReader, streamWriter, csvWriter)); } }
public void WriteCSVFile(string path, List <Movie> mv) { using (StreamWriter sw = new StreamWriter(path, false, new UTF8Encoding(true))) { using (var cw = new CsvHelper.CsvWriter(sw, System.Globalization.CultureInfo.CurrentCulture)) { cw.WriteHeader <Movie>(); cw.NextRecord(); foreach (Movie stu in mv) { cw.WriteRecord <Movie>(stu); cw.NextRecord(); } } } }
public static string CreateCSV(IEnumerable <StringTableEntry> entries) { using (var textWriter = new System.IO.StringWriter()) { // Generate the localised .csv file // Use the invariant culture when writing the CSV var csv = new CsvHelper.CsvWriter( textWriter, // write into this stream GetConfiguration() // use this configuration ); csv.WriteRecords(entries); return(textWriter.ToString()); } }
public void CsvHelper() { using (var str = new StringWriter()) { using (var csv = new CH.CsvWriter(str)) { csv.WriteHeader <Row>(); csv.NextRecord(); for (var i = 0; i < Repeat; i++) { csv.WriteRecords(ToWrite); } } GC.KeepAlive(str.ToString()); } }
/// <summary> /// /// </summary> /// <param name="options"></param> /// <param name="hits"></param> private static void PrintHits(Options options, List<Hit> hits) { try { CsvHelper.CsvWriterOptions csvWriterOptions = SetCsvWriterConfig(options); using (MemoryStream memoryStream = new MemoryStream()) using (StreamWriter streamWriter = new StreamWriter(memoryStream)) using (CsvHelper.CsvWriter csvWriter = new CsvHelper.CsvWriter(streamWriter, csvWriterOptions)) { // Write out the file headers csvWriter.WriteField("Last Modified"); csvWriter.WriteField("Last Update"); csvWriter.WriteField("Path"); csvWriter.WriteField("File Size"); csvWriter.WriteField("Process Exec Flag"); csvWriter.NextRecord(); var sorted = GetSortedHits(options, hits); foreach (Hit hit in sorted) { switch (hit.Type) { case Global.CacheType.CacheEntryXp: // Windows XP Shim Cache csvWriter.WriteField(hit.LastModified.ToShortDateString() + " " + hit.LastModified.ToShortTimeString()); csvWriter.WriteField(hit.LastUpdate.ToShortDateString() + " " + hit.LastUpdate.ToShortTimeString()); csvWriter.WriteField(hit.Path); csvWriter.WriteField(hit.FileSize.ToString()); csvWriter.WriteField(hit.ProcessExecFlag); csvWriter.NextRecord(); break; case Global.CacheType.CacheEntryNt5: // Windows 2k3/Vista/2k8 Shim Cache case Global.CacheType.CacheEntryNt6: // Windows 7/2k8-R2 Shim Cache csvWriter.WriteField(hit.LastModified.ToShortDateString() + " " + hit.LastModified.ToShortTimeString()); csvWriter.WriteField("N/A"); csvWriter.WriteField(hit.Path); csvWriter.WriteField("N/A"); csvWriter.WriteField(hit.ProcessExecFlag); csvWriter.NextRecord(); break; } } string output = string.Empty; memoryStream.Position = 0; using (StreamReader streamReader = new StreamReader(memoryStream)) { output = streamReader.ReadToEnd(); } Console.Write(output); if (options.Output.Length > 0) { string ret = IO.WriteUnicodeTextToFile(output, options.Output, false); if (ret.Length > 0) { } } } } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); } }
/// <summary> /// /// </summary> /// <param name="options"></param> /// <param name="cacheEntries"></param> private static void PrintCacheEntries(Options options, List<CacheEntry> cacheEntries) { try { CsvHelper.CsvWriterOptions csvWriterOptions = SetCsvWriterConfig(options); using (MemoryStream memoryStream = new MemoryStream()) using (StreamWriter streamWriter = new StreamWriter(memoryStream)) using (CsvHelper.CsvWriter csvWriter = new CsvHelper.CsvWriter(streamWriter, csvWriterOptions)) { // Write out the file headers csvWriter.WriteField("File Path"); csvWriter.WriteField("File Name"); csvWriter.WriteField("URL"); csvWriter.WriteField("Codebase IP"); csvWriter.WriteField("Headers"); csvWriter.WriteField("Content Length"); csvWriter.WriteField("Modified"); csvWriter.WriteField("Expiration"); csvWriter.WriteField("Validation"); csvWriter.NextRecord(); var sorted = GetSortedCacheEntries(options, cacheEntries); StringBuilder text = new StringBuilder(); foreach (CacheEntry cacheEntry in sorted) { text.AppendFormat("File Path: {0}{1}", cacheEntry.FilePath, Environment.NewLine); text.AppendFormat("File Name: {0}{1}", cacheEntry.FileName, Environment.NewLine); text.AppendFormat("URL: {0}{1}", cacheEntry.Url, Environment.NewLine); text.AppendFormat("Codebase IP: {0}{1}", cacheEntry.CodebaseIp, Environment.NewLine); text.AppendFormat("Headers: {1}{0}", cacheEntry.HeadersText, Environment.NewLine); text.AppendFormat("Content Length: {0}{1}", cacheEntry.ContentLength, Environment.NewLine); if (cacheEntry.LastModified.Year == 1970 | cacheEntry.LastModified.Year == 0001) { text.AppendFormat("Modified: {0}{1}", string.Empty, Environment.NewLine); } else { text.AppendFormat("Modified: {0}{1}", cacheEntry.LastModified.ToShortDateString() + " " + cacheEntry.LastModified.ToShortTimeString(), Environment.NewLine); } if (cacheEntry.ExpirationDate.Year == 1970 | cacheEntry.ExpirationDate.Year == 0001) { text.AppendFormat("Expiration: {0}{1}", string.Empty, Environment.NewLine); } else { text.AppendFormat("Expiration: {0}{1}", cacheEntry.ExpirationDate.ToShortDateString() + " " + cacheEntry.ExpirationDate.ToShortTimeString(), Environment.NewLine); } if (cacheEntry.ValidationTimestamp.Year == 1970 | cacheEntry.ValidationTimestamp.Year == 0001) { text.AppendFormat("Validation: {0}{1}", string.Empty, Environment.NewLine); } else { text.AppendFormat("Validation: {0}{1}", cacheEntry.ValidationTimestamp.ToShortDateString() + " " + cacheEntry.ValidationTimestamp.ToShortTimeString(), Environment.NewLine); } text.AppendLine(string.Empty); csvWriter.WriteField(cacheEntry.FilePath); csvWriter.WriteField(cacheEntry.FileName); csvWriter.WriteField(cacheEntry.CodebaseIp); csvWriter.WriteField(cacheEntry.Url); csvWriter.WriteField(cacheEntry.HeadersText); csvWriter.WriteField(cacheEntry.ContentLength); if (cacheEntry.LastModified.Year == 1970 | cacheEntry.LastModified.Year == 0001) { csvWriter.WriteField(string.Empty); } else { csvWriter.WriteField(cacheEntry.LastModified.ToShortDateString() + " " + cacheEntry.LastModified.ToShortTimeString()); } if (cacheEntry.ExpirationDate.Year == 1970 | cacheEntry.ExpirationDate.Year == 0001) { csvWriter.WriteField(string.Empty); } else { csvWriter.WriteField(cacheEntry.ExpirationDate.ToShortDateString() + " " + cacheEntry.ExpirationDate.ToShortTimeString()); } if (cacheEntry.ValidationTimestamp.Year == 1970 | cacheEntry.ValidationTimestamp.Year == 0001) { csvWriter.WriteField(string.Empty); } else { csvWriter.WriteField(cacheEntry.ValidationTimestamp.ToShortDateString() + " " + cacheEntry.ValidationTimestamp.ToShortTimeString()); } csvWriter.NextRecord(); } string output = string.Empty; memoryStream.Position = 0; using (StreamReader streamReader = new StreamReader(memoryStream)) { output = streamReader.ReadToEnd(); } Console.Write(text); if (options.Output.Length > 0) { string ret = IO.WriteTextToFile(output, options.Output, false); if (ret.Length > 0) { Console.Write("An error occurred whilst outputting the CSV/TSV file: " + ret); } } } } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); } }