public void record_number_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => writer.RecordNumber); }
/// <summary> /// Write headers to CSV file that doesn't have headers. /// </summary> /// <typeparam name="T">Model class param.</typeparam> /// <param name="_streamWriter">A StreamWriter param.</param> public static void addHeaderToCSVFile <T>(StreamWriter _streamWriter) { writer = new CsvWriter(_streamWriter, CultureInfo.InvariantCulture); writer.WriteHeader <T>(); writer.NextRecord(); writer.Dispose(); }
public void Update(Person p) { StreamReader sr; List <Person> li = new List <Person>(); try { sr = new StreamReader(path); var csvr = new CsvReader(sr); li = csvr.GetRecords <Person>().ToList(); csvr.Dispose(); sr.Close(); } catch (Exception) { } for (int i = 0; i < li.Count; ++i) { if (li[i].Id == p.Id) { li.RemoveAt(i); li.Insert(i, p); break; } } StreamWriter sw = new StreamWriter(path); var csv = new CsvWriter(sw); csv.WriteRecords(li); csv.Dispose(); sw.Close(); }
public async Task write_record_async_values_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); await Assert.ThrowsAsync <ObjectDisposedException>(() => writer.WriteRecordAsync("one", "two", "three")); }
/// <summary> /// Append collection to available CSV file. /// </summary> /// Below is an usage example. /// <example> /// <code> /// Inside the file before appended : /// name,email,address /// someName1,someEmail1,someAddress1 /// /// /// TestModel anObject = new TestModel() { /// name = someName3, /// email = someEmail3, /// address = someAddress3 /// }; /// /// CSVOperation.appendToFile<TestModel>(TextOperation.getStreamWriterFile("C:\\path\\to\\file.csv"), collection); /// </code> /// </example> /// Output (inside file). /// <code> /// name,email,address /// someName1,someEmail1,someAddress1 /// someName3,someEmail3,someAddress3 /// </code> /// <typeparam name="T"></typeparam> /// <param name="_appendWriter"></param> /// <param name="_collection"></param> public static void appendToFile <T>(StreamWriter _appendWriter, T _item) { writer = new CsvWriter(_appendWriter, CultureInfo.InvariantCulture); writer.Configuration.HasHeaderRecord = false; writer.WriteRecord(_item); writer.Dispose(); }
public void CsvWriterTest() { var buffer = new StringBuilder(); var writer = new CsvWriter(new StringWriter(buffer)); writer.WriteRecord("One", "Two", "Three"); writer.WriteRecord(); // blank line writer.WriteRecord("QuoteChar", new string(writer.QuoteChar, 1)); writer.WriteRecord("FieldSeparator", new string(writer.FieldSeparator, 1)); writer.WriteRecord("a\"b\"c", "line\nbreak", "line\rbreak", "line\r\nbreak"); writer.WriteRecord(" leading", "trailing ", " blanks "); writer.Dispose(); var ex = Assert.Catch(() => writer.WriteRecord()); Console.WriteLine(@"Expected exception: {0}", ex.Message); const string expected = "One,Two,Three\r\n" + "\r\n" + "QuoteChar,\"\"\"\"\r\n" + "FieldSeparator,\",\"\r\n" + "\"a\"\"b\"\"c\",\"line\nbreak\",\"line\rbreak\",\"line\r\nbreak\"\r\n" + "\" leading\",\"trailing \",\" blanks \"\r\n"; Assert.AreEqual("\r\n", Environment.NewLine); Assert.AreEqual(expected, buffer.ToString()); }
public void WriteRecordTest3() { using var writer = new CsvWriter("File", 2); writer.Dispose(); writer.WriteRecord(); }
public void write_csv_throws_if_csv_writer_is_disposed() { var writer = new CsvWriter(new StringWriter()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => new DateTime[0].WriteCsv(writer)); }
public async Task write_record_async_record_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); await Assert.ThrowsAsync <ObjectDisposedException>(() => writer.WriteRecordAsync(new HeaderRecord())); }
public void Write(IEnumerable <IRow> rows) { var csv = new CsvWriter(_streamWriter, Config); try { if (_context.Connection.Header == Constants.DefaultSetting) { WriteHeader(csv); csv.NextRecord(); } foreach (var row in rows) { WriteRow(csv, row); _context.Entity.Inserts++; csv.NextRecord(); } } finally { if (csv != null) { csv.Flush(); csv.Dispose(); } } }
public async Task write_csv_async_throws_if_csv_writer_is_disposed() { var writer = new CsvWriter(new StringWriter()); writer.Dispose(); await Assert.ThrowsAsync <ObjectDisposedException>(() => new DateTime[0].WriteCsvAsync(writer)); }
public void Save(string filename = "calib.txt") { var writer = new CsvWriter(filename); writer.Write(model.Coef); writer.Dispose(); }
public void new_line_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => writer.NewLine); }
public void write_record_record_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => writer.WriteRecord(new HeaderRecord())); }
private void saveButton_Click(object sender, EventArgs e) { StreamWriter outFile = File.CreateText(inputFilePath); CsvWriter writer = new CsvWriter(outFile, CultureInfo.InvariantCulture); foreach (DataColumn item in this.dataSource.Columns) { writer.WriteField(item.ColumnName); } writer.NextRecord(); foreach (DataRow item in this.dataSource.Rows) { List <string> values = item.ItemArray.Cast <Object>().Select(p => { if (p.GetType() == typeof(System.DBNull)) { return(""); } return(p); }).Cast <string>().ToList(); foreach (string attribute in values) { writer.WriteField(attribute); } writer.NextRecord(); } writer.Dispose(); outFile.Dispose(); }
public async Task flush_async_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); await Assert.ThrowsAsync <ObjectDisposedException>(() => writer.FlushAsync()); }
/// <summary> /// 設定ウィンドウ内で表示されている項目をCSVでエクスポートする。 /// </summary> /// <typeparam name="TMaptype">CsvClassMap型</typeparam> /// <param name="records">エクスポートするデータ</param> /// <param name="defaultFileName">デフォルトのファイル名(.csvと付けること)</param> public void CsvExport <TMaptype>(List <object> records, string defaultFileName) where TMaptype : CsvHelper.Configuration.ClassMap { var saveFileDialog = new SaveFileDialog { Title = Resources.SelectSaveDestination, InitialDirectory = @"C:\", Filter = "CSV|*.csv", CreatePrompt = true, FileName = defaultFileName }; if (!saveFileDialog.ShowDialog() ?? false) { return; } try { var csvWriter = new CsvWriter(new StreamWriter(saveFileDialog.FileName, false, Encoding.UTF8)); csvWriter.Configuration.HasHeaderRecord = false; csvWriter.Configuration.RegisterClassMap <TMaptype>(); csvWriter.WriteRecords(records); csvWriter.Dispose(); MessageBox.Show(Resources.SuccessfulExport, Properties.Resources.AppName, MessageBoxButton.OK); } catch (Exception e) { MessageBox.Show(Resources.ExportFailed + e, Properties.Resources.AppName, MessageBoxButton.OK); } }
public override void Dispose() { if (_writer != null) { _writer.Dispose(); } }
/// <summary> /// Writes the records into CSV /// </summary> /// <param name="records">The records.</param> /// <param name="filePath">The file path.</param> /// <param name="delimiter">The delimiter.</param> /// <param name="append">If true, append.</param> public static void WriteRecords <T>( this List <T> records, string filePath, string delimiter = ",", bool append = false ) { Log.Information ( "Writing {Count} rows to {FilePath}", records.Count, filePath ); var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = delimiter, HasHeaderRecord = false }; var writer = new StreamWriter(filePath); if (append) { var stream = File.Open(filePath, FileMode.Append); writer = new StreamWriter(stream); } var csv = new CsvWriter(writer, config); csv.WriteRecords(records); Log.Debug("CSV file written to {FilePath}", filePath); writer.Dispose(); csv.Dispose(); }
public void write_record_values_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => writer.WriteRecord("one", "two", "three")); }
static void Main(string[] args) { CsvReader reader = new CsvReader(new StreamReader(inputFileCsv)); IEnumerable <WordRecord> allwords = reader.GetRecords <WordRecord>().ToList(); reader.Dispose(); string[] filters = File.ReadAllLines(filterFile); HashSet <string> filterHash = new HashSet <string>(from s in filters let lower = s.Trim().ToLower() where IsSingleWord(lower) select lower); List <WordRecord> filteredWords = (from w in allwords where w != null let lower = w.Word.Trim().ToLower() where filterHash.Contains(lower) select new WordRecord() { Word = lower, Tag = w.Tag, Response = w.Response }).ToList(); Dictionary <string, WordRecord> filterDict = new Dictionary <string, WordRecord>(); foreach (WordRecord w in filteredWords) { if (!filterDict.ContainsKey(w.Word)) { filterDict[w.Word] = w; } } CsvWriter writer = new CsvWriter(new StreamWriter(outputFileCsv)); writer.WriteRecords(from w in filterDict.Values orderby w.Tag, w.Word select w); writer.Dispose(); }
public void Save(List <MBall> balls, string FilePath) { CsvWriter csv = new CsvWriter(new StreamWriter(FilePath)); csv.WriteRecords(balls); csv.Dispose(); }
/// <summary> /// 設定ウィンドウ内で表示されている項目をCSVでエクスポートする。 /// </summary> /// <typeparam name="TMaptype">CsvClassMap型</typeparam> /// <param name="bindableData">エクスポートするデータ</param> /// <param name="defaultFileName">デフォルトのファイル名(.csvと付けること)</param> public void CsvExport <TMaptype>(BindingSource bindableData, string defaultFileName) where TMaptype : CsvHelper.Configuration.CsvClassMap { var saveFileDialog = new SaveFileDialog { Title = "保存先を選択してください。", InitialDirectory = @"C:\", Filter = "CSV|*.csv", CreatePrompt = true, FileName = defaultFileName }; if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { var csvWriter = new CsvWriter(new StreamWriter(saveFileDialog.FileName, false, Encoding.GetEncoding("Shift_JIS"))); csvWriter.Configuration.HasHeaderRecord = false; csvWriter.Configuration.RegisterClassMap <TMaptype>(); csvWriter.WriteRecords(bindableData); csvWriter.Dispose(); MessageBox.Show("エクスポートが完了しました。"); } catch (Exception e) { MessageBox.Show("エクスポートに失敗しました" + e); } } saveFileDialog.Dispose(); }
public void flush_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => writer.Flush()); }
public override void Dispose() { base.Dispose(); _csvWriter?.Dispose(); _textWriter?.Dispose(); }
public async Task write_records_async_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); await Assert.ThrowsAsync <ObjectDisposedException>(() => writer.WriteRecordsAsync(new RecordBase[1], 0, 1)); }
public void value_separator_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => writer.ValueSeparator); }
public void write_records_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => writer.WriteRecords(new RecordBase[1], 0, 1)); }
public void force_delimit_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws <ObjectDisposedException>(() => writer.ForceDelimit); }
private static void Dispose() { Log.LogMessage("Cleaning up..."); if (_context != null) { _context.Dispose(); _context = null; } if (_csvWriter != null) { _csvWriter.Dispose(); _csvWriter = null; } if (_log != null) { _log.Dispose(); _log = null; } if (_cursor != null) { _cursor.Dispose(); _cursor = null; } if (_httpClient != null) { _httpClient.Dispose(); _httpClient = null; } }
public virtual ActionResult SubmitResponses(List<TallySheet> results) { if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\PitData")) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\PitData"); } var current = DateTime.Now; var pitWriter = new StreamWriter( string.Format( AppDomain.CurrentDomain.BaseDirectory + "\\PitData\\TallySheet-{0}-{1}-{2}-{3}{4}{5}.csv", current.Day, current.Month, current.Year, current.Hour, current.Minute, current.Millisecond)); var pitCsv = new CsvWriter(pitWriter); pitCsv.Configuration.HasHeaderRecord = true; pitCsv.WriteField("Id"); pitCsv.WriteField("Notes"); pitCsv.WriteField("Created"); pitCsv.WriteField("CreatedBy"); pitCsv.WriteField("Latitude"); pitCsv.WriteField("Longitude"); pitCsv.WriteField("Gender"); pitCsv.WriteField("Age"); pitCsv.WriteField("Family"); pitCsv.WriteField("Dwelling"); pitCsv.WriteField("Location"); pitCsv.NextRecord(); var ids = new List<int>(); foreach (var result in results) { if (result.SubmitThis) { if (result.IsTallySheet) { var pit = db.PITs.Find(result.Id); pit.Notes = result.Notes; pit.SubmissionDate = DateTime.Now; db.SaveChanges(); pitCsv.WriteField(pit.PITId); pitCsv.WriteField(pit.Notes, true); pitCsv.WriteField(pit.CreatedDate); pitCsv.WriteField(pit.User.FirstName + " " + pit.User.LastName); pitCsv.WriteField(pit.Latitude); pitCsv.WriteField(pit.Longitude); pitCsv.WriteField(pit.GenderAnswer, true); pitCsv.WriteField(pit.AgeAnswer, true); pitCsv.WriteField(pit.FamilyAnswer, true); pitCsv.WriteField(pit.DwellingAnswer, true); pitCsv.WriteField(pit.LocationAnswer, true); pitCsv.NextRecord(); } else { var sqlStatment = "update ClientSurveys set Notes=@Notes, SubmissionDate=@SubmissionDate where ClientSurveyId = @Id"; var notes = new SqlParameter("Notes", !string.IsNullOrEmpty(result.Notes) ? result.Notes : " "); var submissionDate = new SqlParameter("SubmissionDate", DateTime.Now); var id = new SqlParameter("Id", result.Id); ids.Add(result.Id); db.Database.ExecuteSqlCommand(sqlStatment, new[] {notes, submissionDate, id}); } } } var css = db.ClientSurveys.Where(x => ids.Contains(x.ClientSurveyId)).Include(x => x.Client).Include(x=>x.User); if (css.Any()) { var allQuestions = db.SurveyQuestions.Where(s => s.SurveyId == css.FirstOrDefault().SurveyId) .Include(sq => sq.Question) .Select(s => s.Question); var questionIds = allQuestions.Select(q => q.QuestionId).ToList(); var surveyWriter = new StreamWriter( string.Format( AppDomain.CurrentDomain.BaseDirectory + "\\PitData\\PitSurvey-{0}-{1}-{2}-{3}{4}{5}.csv", current.Day, current.Month, current.Year, current.Hour, current.Minute, current.Millisecond)); var surveyCsv = new CsvWriter(surveyWriter); surveyCsv.Configuration.HasHeaderRecord = true; surveyCsv.WriteField("Id"); surveyCsv.WriteField("Notes"); surveyCsv.WriteField("Created"); surveyCsv.WriteField("CreatedBy"); surveyCsv.WriteField("Latitude"); surveyCsv.WriteField("Longitude"); foreach (var qId in questionIds) { var quest = allQuestions.FirstOrDefault(q => q.QuestionId == qId); if (quest != null) { surveyCsv.WriteField(quest.QuestionText, true); } } surveyCsv.NextRecord(); foreach (var cs in css) { surveyCsv.WriteField(cs.ClientSurveyId); surveyCsv.WriteField(cs.Notes, true); surveyCsv.WriteField(cs.SurveyDate); surveyCsv.WriteField(cs.User.FirstName + " " + cs.User.LastName); surveyCsv.WriteField(cs.Client.Latitude); surveyCsv.WriteField(cs.Client.Longitude); foreach (var qId in questionIds) { var csr = cs.Responses.FirstOrDefault(c => c.QuestionId == qId); surveyCsv.WriteField(csr != null ? csr.Value : "", true); } surveyCsv.NextRecord(); } surveyCsv.Dispose(); } pitCsv.Dispose(); return RedirectToAction(MVC.Pit.TallySheets()); }
private void readCSV(string link) { try { using (TextReader reader = File.OpenText(link)) { CsvConfiguration config = new CsvConfiguration() { Delimiter = ",", QuoteAllFields = false, IgnoreHeaderWhiteSpace = true, IsHeaderCaseSensitive = true }; var csv = new CsvReader(reader, config); ReadLine(reader, 6); var records = csv.GetRecords<InSetup>(); string newlink = link.Remove(link.Length - 4) + "-new.csv"; TextWriter tw = File.CreateText(newlink); var writer = new CsvWriter(tw); writer.WriteField("Date"); writer.WriteField("Description"); writer.WriteField("Amount"); writer.WriteField("Type"); writer.NextRecord(); foreach (InSetup record in records) { //write record field by field writer.WriteField(record.Date); string description = GetDescription(record); writer.WriteField(description); string amount = PosAmount(record.Amount.ToString()); writer.WriteField(amount); string classification = Classify(description); writer.WriteField(classification); //ensure you write end of record when you are using WriteField method writer.NextRecord(); } writer.Dispose(); reader.Dispose(); reader.Close(); MessageBox.Show("All Done!"); } } catch (CsvMissingFieldException e) { MessageBox.Show("Please remove any spaces in the CSV headers"); } catch (IOException e) { MessageBox.Show("File is being used by another program. Cannot open"); } }
public void flush_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.Flush()); }
public async Task write_records_async_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(() => writer.WriteRecordsAsync(new RecordBase[1], 0, 1)); }
public void value_separator_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.ValueSeparator); }
public async Task flush_async_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(() => writer.FlushAsync()); }
public void Save(List<BouncingBallClass> balls, string FilePath) { CsvWriter csv = new CsvWriter(new StreamWriter(FilePath)); csv.WriteRecords(balls); csv.Dispose(); }
public void force_delimit_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.ForceDelimit); }
public void record_number_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.RecordNumber); }
public void write_records_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.WriteRecords(new RecordBase[1], 0, 1)); }
public void write_record_values_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.WriteRecord("one", "two", "three")); }
public async Task write_record_async_values_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(() => writer.WriteRecordAsync("one", "two", "three")); }
public void new_line_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.NewLine); }
public async Task write_record_async_record_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(() => writer.WriteRecordAsync(new HeaderRecord())); }
public void Save(List<ShapeData> balls, string FilePath) { CsvWriter csv = new CsvWriter(new StreamWriter(FilePath)); csv.WriteRecords(balls); csv.Dispose(); }
public void write_record_record_throws_if_disposed() { var writer = new CsvWriter(new MemoryStream()); writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.WriteRecord(new HeaderRecord())); }