Having the following function:
string chargeMonth = DateTime.Now.ToString("yyyyMM");
var fileCreationDate = DateTime.Now.ToString("yyyyMMdd");
string fileCreationTime = DateTime.Now.ToString("HHmmss");
string constVal = "MLL";
string fileType = "HIYUV-CHEVRA";
string[] values;
string header, sumRow;
string line, compId;
string inputFile = "records.CSV";
Dictionary<string, System.IO.StreamWriter> outputFiles = new Dictionary<string, System.IO.StreamWriter>();
using (System.IO.StreamReader file = new System.IO.StreamReader("D:\\" + inputFile, Encoding.Default))
{
header = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
values = line.Split(",".ToCharArray());
compId = values[3];
if (!outputFiles.ContainsKey(compId))
{
sumRow = constVal + "-" + fileType + "-" + (String.Format("{0:00000}", Int32.Parse(compId))) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime;
string outputFileName = constVal + "-" + fileType + "-" + (String.Format("{0:00000}", Int32.Parse(compId))) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime + ".CSV";
outputFiles.Add(compId, new System.IO.StreamWriter("D:\\" + outputFileName));
outputFiles[compId].WriteLine(header);
}
outputFiles[compId].WriteLine(line);
}
}
foreach (System.IO.StreamWriter outputFile in outputFiles.Values)
{
outputFile.Close();
}
Which will create csvs based on dictionary's keys/values.
anyways, for each CSV I want to add a row in the FIRST line which is not in a format of the other rows..
somehting like:
line1 aaaabbbbcccc
line2 1 2 3 10 100
line3 2 2 3 10 100
I have no idea how to do that since Im "pulling" data from a dictionary and the line has nothing to do with it. Thanks for any kind of help.
outputFiles[compId].WriteLine(constVal + "-" + fileType + "-" + (String.Format("{0:00000}", Int32.Parse(compId))) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime + ".CSV");
added the following line, it works now. thanks.
Related
I'm working on a bit of code for school but I keep getting an ArgumentOutOfRangeException
With this code I'm trying to read some data from a .csv file and if it equals the name of the image I want it to remove it from the .csv file whilst keeping the structure intact.
public void checkPair(Image card1, Image card2)
{
this.Image1 = card1;
this.Image2 = card2;
if (Convert.ToString(card1.Source) == Convert.ToString(card2.Source) && (card1 != card2))
{
getPoint(card1, card2);
string path = #"Save1.csv";
var reader = new StreamReader(File.OpenRead(path));
var data = new List<List<string>>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');
data.Add(new List<String> { values[0], values[1]
});
}
reader.Close();
string delimiter = ";";
for (int i = 1; i < 5; i++)
{
for (int x = 0; x < 4; x++)
{
if (data[i][x] == Convert.ToString(card1.Source))
{
data[i][x] = null;
}
}
}
File.WriteAllText(path, data[0][0] + delimiter + data[0][1] + Environment.NewLine + data[1][0] + delimiter + data[1][1] + delimiter + data[1][2] + delimiter + data[1][3] + Environment.NewLine + data[2][0] + delimiter + data[2][1] + delimiter + data[2][2] + delimiter + data[2][3] + Environment.NewLine + data[3][0] + delimiter + data[3][1] + delimiter + data[3][2] + delimiter + data[3][3] + Environment.NewLine + data[4][0] + delimiter + data[4][1] + delimiter + data[4][2] + delimiter + data[4][3] + Environment.NewLine + "ready");
I have no idea why I get this error and how to fix it
Initially, I'd change your last line from
File.WriteAllText(path, data[0][0] + delimiter + data[0][1] ....
to something like
var obj1 = data[0][0];
var obj2 = data[0][1];
File.WriteAllText(path, obj1 + delimiter + obj2 .... etc)
If you over inline functions or array accessing, when you get an exception the stack trace won't be that helpful. At least you'll have an idea of the statement that caused the issue.
This technique can prove to be very helpful, if you are looking at an in exception in the logs, after the fact.
I can't seem to be able to delete files after a streamreader use, with a
"file can't be accessed because file is in use"
error in C#.
I may miss something but I don't know what, here is the code :
fileEntries = from fullFilename
in Directory.EnumerateFiles(#"Data\csv\pending")
select Path.GetFileName(fullFilename);
i = 1;
foreach (string file in fileEntries)
{
if(i == 1)
{
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.FileStream fs = System.IO.File.Create(folder + #"\create-user.csv"))
{
}
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user.csv", true))
{
files.WriteLine(",; prenom; nom; username; pasword; email; question; reponse; GroupID");
}
string curfile = #"\create-user-archive.csv";
if(!(File.Exists(folder + curfile)))
{
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user-archive.csv", true))
{
files.WriteLine(",; prenom; nom; username; pasword; email; question; reponse; GroupID");
}
}
}
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\pending";
sb = new StringBuilder();
filef = new System.IO.StreamReader(folder + #"\create-user-" + i + ".csv");
line = filef.ReadLine();
while ((line = filef.ReadLine()) != null)
{
sb = new StringBuilder();
sb.AppendLine(line.Substring(0, line.Length));
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user.csv", true))
{
files.WriteLine(",; " + sb.ToString().Split(';')[1] + ";" + sb.ToString().Split(';')[2] + ";" + sb.ToString().Split(';')[1] + "." + sb.ToString().Split(';')[2] + ";" + GenerateToken(6) + ";" + sb.ToString().Split(';')[3] + ";" + "1" + ";" + "1");
}
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user-archive.csv", true))
{
files.WriteLine(",; " + sb.ToString().Split(';')[1] + ";" + sb.ToString().Split(';')[2] + ";" + sb.ToString().Split(';')[1] + "." + sb.ToString().Split(';')[2] + ";" + GenerateToken(6) + ";" + sb.ToString().Split(';')[3] + ";" + "1" + ";" + "1");
}
}
i++;
sourceFile = System.IO.Path.Combine(#"Data\csv\pending", file);
File.Delete(sourceFile);
}
shouldn't the file stop being in use after the streamreader is finished? I tried using a function that waits until the file is unlocked to delete the file, but it is infinite, which means there is a never ending process that I must stop, but I don't see which one.
You need to close filef.
Wrapping the code in a using statement will automatically close the reader
using ( System.IO.StreamReader filef = new System.IO.StreamReader(folder + #"\create-user-" + i + ".csv") {
....yourcodehere
}
Alternatively, call filef.Close() when you are done with it (before you delete the file)
You have to close the streams you create to dispose the system resources. You can either use the Close method or the using pattern, as the classes implemented IDisposable interface. I would recommend you to the second option.
May have a look to this post: https://stackoverflow.com/a/707339/6244709
You will need to call the following;
filef.Close();
This would go before your delete;
while ((line = filef.ReadLine()) != null)
{
sb = new StringBuilder();
sb.AppendLine(line.Substring(0, line.Length));
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user.csv", true))
{
files.WriteLine(",; " + sb.ToString().Split(';')[1] + ";" + sb.ToString().Split(';')[2] + ";" + sb.ToString().Split(';')[1] + "." + sb.ToString().Split(';')[2] + ";" + GenerateToken(6) + ";" + sb.ToString().Split(';')[3] + ";" + "1" + ";" + "1");
}
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user-archive.csv", true))
{
files.WriteLine(",; " + sb.ToString().Split(';')[1] + ";" + sb.ToString().Split(';')[2] + ";" + sb.ToString().Split(';')[1] + "." + sb.ToString().Split(';')[2] + ";" + GenerateToken(6) + ";" + sb.ToString().Split(';')[3] + ";" + "1" + ";" + "1");
}
}
i++;
sourceFile = System.IO.Path.Combine(#"Data\csv\pending", file);
filef.Close();
File.Delete(sourceFile);
I have a bool that the compiler says does not exist in the current scope, however all the other variable are declared and used in the same place/way. Code below, some class names changed and code simplified but the structure remains the same.
iDReq does not exist in the current context
if (button.Click) {
string sourceFileName = "";
string destPathFileName = "";
int exportCount = 0;
bool iDReq = true;
iDReq = (System.Windows.Forms.MessageBox.Show("Include ID in file names?", "ID",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes);
foreach (KeyValueCollection item in SearchControl.SelectedItems)
{
Class.Document doc = Class.Document.GetDocument((long)item["id"].Value);
{
sourceFileName = #"\\server\share" + #"\" + Convert.ToString(doc.GetExtraInfo("docFileName"));
string fileExtension = System.IO.Path.GetExtension(sourceFileName);
//Line below is the one that the compiler does not like.
iDReq = true ? destPathFileName = destPath + #"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension : destPathFileName = destPath + #"" + doc.Description + fileExtension;
try {
System.IO.Directory.CreateDirectory(destPath);
System.IO.File.Copy(sourceFileName,destPathFileName,true);
System.Windows.Forms.Clipboard.SetText(destPathFileName);
exportCount ++;
}
catch(Exception ex)
{
ErrorBox.Show(ex);
}
}
}
}
Is it because it's a boolean value or am I missing something else?
I think your ternary is badly written, but I am not sure about what you want. I would rewrite you this as a plain if/else. I love ternary operator, but it is just sugar.
I think you are looking for this:
destPathFileName = iDReq == true
? (destPath + #"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension)
: (destPath + #"" + doc.Description + fileExtension);
and iDReq == true is superflous.
also you can write:
destPathFileName = destPath + #"" + doc.Description
+ (iDReq ? " (" + doc.ID + ")" : string.Empty)
+ fileExtension;
by the way, #"" is string.Empty.
and with string interpolation:
destPathFileName = destPath + doc.Description
+ (iDReq ? $" ({doc.ID})" : string.Empty)
+ fileExtension;
try this:
destPathFileName = iDReq ? destPath + #"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension : destPath + #"" + doc.Description + fileExtension;
Having trouble figuring out how to prevent the last key in my array to not have a comma. Since its being exported to a .Json file the last key shouldn't have a ",".
I know you can detect it by using .Last();, but I can't seem to make that work. Any recommendations?
//Data Path
string dataPath = #"..\..\FileIOExtraFiles\DataFieldsLayout.txt";
string[] dataList = File.ReadAllLines(dataPath);
//save Data data
using (StreamWriter outStream = new StreamWriter(outputFolder + #"\CharacterStringData3.json"))
{
outStream.WriteLine("{");
for (int i = 0; i < dataFile.Length; i++)
{
string s = dataFile[i];
char last = s.Last();
if (s == "")
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
}
else
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\",");
}
}
outStream.WriteLine("}");
}
Output:
{
"data1":"item1",
"data2":item2",
"lastKey":item3",//trying to remove comma from last key in array.
}
As others have pointed out, it doesn't make sense that you are building json manually, but given that this is a question more about technique, here is one approach: you could change it to this:
var commaSuffix = (i == dataFile.Length - 1) ? "," : string.Empty;
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\"" + commaSuffix);
The suffix would be used on every iteration except the last.
Change this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
To this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \""+(i==dataFile.Length?",":""));
Instead of using outStream.WriteLine() at every step, store it in a string. Then you can remove the last comma from that string and write the whole string at once:
//Get last index of comma
int lastCommaIndex = outputString.LastIndexOf(',');
//Create new StringBuilder with everything before the last comma
StringBuilder sb = new StringBuilder(outputString.Substring(0,lastCommaIndex));
//Add everything after the last comma, or just add a closing brace
//sb.Append("}"); //This instead of next line
sb.Append(outputString.Substring(lastCommaIndex+1));
//Add contents of StringBuilder to the Stream
outSteam.WriteLine(sb);
I'm having issues with a C# Winforms file IO. The code complies just fine, but then it returns errors on execution.
The output code is here:
private void saveData()
{
string fullPath = System.Environment.GetEnvironmentVariable(#"%MyDocuments%\HellsingRPG\");
StreamWriter writer = new StreamWriter(fullPath + textBox2.Text + ".txt");
writer.WriteLine(textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + "," + comboBox1.SelectedText + "," +
numericUpDown25.Value + "," + numericUpDown1.Value + "," + numericUpDown2.Value + "," + numericUpDown3.Value + "," + numericUpDown4.Value + "," +
numericUpDown5.Value + "," + numericUpDown6.Value + "," + numericUpDown7.Value + "," + numericUpDown8.Value + "," + numericUpDown9.Value + "," +
numericUpDown10.Value + "," + numericUpDown11.Value + "," + numericUpDown12.Value + "," + numericUpDown13.Value + "," + numericUpDown14.Value
+ "," + numericUpDown15.Value + "," + numericUpDown16.Value + "," + numericUpDown17.Value + "," + numericUpDown18.Value + "," +
numericUpDown19.Value + "," + numericUpDown20.Value + "," + numericUpDown21.Value + "," + numericUpDown22.Value);
writer.Close();
}
And the code to load the data is here:
private void loadData()
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = System.Environment.GetEnvironmentVariable(#"%MyDocuments%\HellsingRPG\");
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
List<string> myData = parseCSV(System.Convert.ToString(myStream));
textBox1.Text = myData[0];
textBox2.Text = myData[1];
textBox3.Text = myData[3];
textBox4.Text = myData[4];
comboBox1.SelectedText = myData[5];
numericUpDown25.Value = System.Convert.ToDecimal(myData[6]);
numericUpDown1.Value = System.Convert.ToDecimal(myData[7]);
numericUpDown2.Value = System.Convert.ToDecimal(myData[8]);
numericUpDown3.Value = System.Convert.ToDecimal(myData[9]);
numericUpDown4.Value = System.Convert.ToDecimal(myData[10]);
numericUpDown5.Value = System.Convert.ToDecimal(myData[11]);
numericUpDown6.Value = System.Convert.ToDecimal(myData[12]);
numericUpDown7.Value = System.Convert.ToDecimal(myData[13]);
numericUpDown8.Value = System.Convert.ToDecimal(myData[14]);
numericUpDown9.Value = System.Convert.ToDecimal(myData[15]);
numericUpDown10.Value = System.Convert.ToDecimal(myData[16]);
numericUpDown11.Value = System.Convert.ToDecimal(myData[17]);
numericUpDown12.Value = System.Convert.ToDecimal(myData[18]);
numericUpDown13.Value = System.Convert.ToDecimal(myData[19]);
numericUpDown14.Value = System.Convert.ToDecimal(myData[20]);
numericUpDown15.Value = System.Convert.ToDecimal(myData[21]);
numericUpDown16.Value = System.Convert.ToDecimal(myData[22]);
numericUpDown17.Value = System.Convert.ToDecimal(myData[23]);
numericUpDown18.Value = System.Convert.ToDecimal(myData[24]);
numericUpDown19.Value = System.Convert.ToDecimal(myData[25]);
numericUpDown20.Value = System.Convert.ToDecimal(myData[26]);
numericUpDown21.Value = System.Convert.ToDecimal(myData[27]);
numericUpDown22.Value = System.Convert.ToDecimal(myData[28]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
And that compiles just fine. But when I use it, I get the following errors:
"Could not find file "C:\Users\collmark\Documents\Visual Studio
2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Release\System.IO.Filestream".
"Error: Could not read file from disk. Original error: Index out of
range. Must be non-negative and less than the size of the collection.
Parameter name: index."
Thanks
your save data seems to save 22 fields while the read expects 28.
I suspect the myData object does not contain the fields index you are trying to read, hence index out of range.
do yourself a favour when printing exception data don't limit yourself to the message but print the whole stack trace, it will tell you which line is faulty giving you a hint at the actual problem.
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.ToString());