我正在创建一个CSV文件,我正在使用C#和CsvHelper来执行此操作。
我的CSV文件每次最终为205行。我确信它应该创建240个条目,这就是我想要的。
似乎停止在205行创建CSV文件。多次运行时,它会产生205条输入的相同结果。有趣的是,它试图写的最后一个字段是一个字母短,我不知道为什么。
以下是完整的代码。
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using CsvHelper;
using System.IO;
namespace PinGenerator
{
class Program
{
static void Main(string[] args)
{
GeneratePins generatePins = new GeneratePins();
generatePins.Start();
Console.ReadLine();
}
}
public class GeneratePins
{
private Dictionary<string, String> pinNumbers = new Dictionary<string, String>();
private List<String> duplicatePinCheck = new List<string>();
private Random random = new Random();
// Runs the sequence for the generation of TimeSpans & Pin Numbers.
// Stores these into JSON / CSV Files
public void Start()
{
TimeSpan timeSpan = new TimeSpan();
TimeSpan maxTime = TimeSpan.FromHours(2);
TimeSpan currentTimeSpan = TimeSpan.FromSeconds(30);
string currentPin = "0000";
// CSV File Creation
TextWriter textWriter = File.CreateText(@"pinNumber.csv");
var csv = new CsvWriter(textWriter);
while (timeSpan.Duration() < maxTime.Duration())
{
// Create TimeSpan & Pin
timeSpan = timeSpan.Add(currentTimeSpan);
currentPin = RandomNumber();
// Duplicate Check
while (duplicatePinCheck.Contains(currentPin))
{
currentPin = RandomNumber();
}
duplicatePinCheck.Add(currentPin);
// Cache Results
string entryPinNumber = currentPin;
string entryTimeSpan = timeSpan.ToString();
// JSON
pinNumbers.Add(entryTimeSpan, currentPin);
// CSV Creation - Write to CSV File
csv.WriteField(entryTimeSpan);
csv.WriteField(entryPinNumber);
csv.NextRecord();
// CONSOLE
Console.WriteLine(entryPinNumber + " / " + timeSpan.ToString());
}
string json = JsonConvert.SerializeObject(pinNumbers, Formatting.Indented);
// Write to JSON File
using (System.IO.StreamWriter file = File.CreateText(@"pinNumbers.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, pinNumbers);
}
Console.WriteLine("Created " + pinNumbers.Count() + " pin numbers.");
}
public string RandomNumber()
{
String result = random.Next(0, 9999).ToString();
result = result.PadLeft(4, '0');
return result;
}
}
}
答案 0 :(得分:1)
TextWriter textWriter = File.CreateText(@"pinNumber.csv");
需要更改为
StreamWriter streamWriter = File.CreateText(@"pinNumber.csv");