CSV file is not being written to - c#

I am trying to write to a CSV file, and have researched a bit on how to do this and it seems pretty straightforward but it is not populating my CSV file when I run it. The program will write to a txt and my console with no issue.
StreamWriter vWriteFile = new StreamWriter("Positions2.csv");
var path = #"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReader3\Position_2016_02_25.0415.csv";
if (vShowBoth == false)
{
//This determines whether to view by account or by underlying.
Console.WriteLine("Please enter 0 if you wish to see sums by account, or 12 if you wish to see by underlying");
int vViewControl = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Account" + " Settle Sum" + " Open Sum" + " Buy Sum" + " Sell Sum");
using (var parsedLines = File.ReadLines(path).Select(line => line.Split(',')).GetEnumerator())
{
bool vMore = parsedLines.MoveNext();
while (vMore)
{
// Initialize
bool vWasSuccessful;
var vAccount = parsedLines.Current[vViewControl];
double vSettleMMSum = 0;
double vOpenSum = 0;
int vBuySum = 0;
int vSellSum = 0;
do
{
double vParseSettleMM = 0;
double vParseOpen = 0;
int vParseBuy = 0;
int vParseSell = 0;
//Parsing data read in from strings, into temp variables
vWasSuccessful = double.TryParse(parsedLines.Current[7], out vParseSettleMM);
vWasSuccessful = double.TryParse(parsedLines.Current[8], out vParseOpen);
vWasSuccessful = int.TryParse(parsedLines.Current[6], out vParseBuy);
vWasSuccessful = int.TryParse(parsedLines.Current[10], out vParseSell);
//adding temp variabels to sum
vSettleMMSum += vParseSettleMM;
vOpenSum += vParseOpen;
vBuySum += vParseBuy;
vSellSum += vParseSell;
vMore = parsedLines.MoveNext();
}
//sets up when to break
while (vMore && vAccount == parsedLines.Current[vViewControl]);
//After each Break need to print out Account name and sums from above.
// Do printing here as part of the loop, at the very end of the loop code block.
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine(vAccount + " " + vSettleMMSum + " " + vOpenSum + " " + vBuySum + " " +
vSellSum);
//vWriteFile.Write(vAccount + "," + vSettleMMSum + "," + vOpenSum + "," + vBuySum + "," +
// vSellSum);
vWriteFile.WriteLine("{0},{1},{2},{3},{4}", vAccount, vSettleMMSum, vOpenSum, vBuySum, vSellSum);
//reset sums for next loop
vSettleMMSum = 0;
vOpenSum = 0;
vBuySum = 0;
vSellSum = 0;
}
}
}

You should make it a habit to wrap your streams with the using keyword so you don't run into situations where you forget to close it out. It's a good practice to use the using keyword around anything that inherits IDisposable
So your code would look like this.
using(StreamWriter vWriteFile = new StreamWriter("Positions2.csv"))
{
var path = #"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReader3\Position_2016_02_25.0415.csv";
if (vShowBoth == false)
{
//This determines whether to view by account or by underlying.
Console.WriteLine("Please enter 0 if you wish to see sums by account, or 12 if you wish to see by underlying");
int vViewControl = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Account" + " Settle Sum" + " Open Sum" + " Buy Sum" + " Sell Sum");
using (var parsedLines = File.ReadLines(path).Select(line => line.Split(',')).GetEnumerator())
{
bool vMore = parsedLines.MoveNext();
while (vMore)
{
// Initialize
bool vWasSuccessful;
var vAccount = parsedLines.Current[vViewControl];
double vSettleMMSum = 0;
double vOpenSum = 0;
int vBuySum = 0;
int vSellSum = 0;
do
{
double vParseSettleMM = 0;
double vParseOpen = 0;
int vParseBuy = 0;
int vParseSell = 0;
//Parsing data read in from strings, into temp variables
vWasSuccessful = double.TryParse(parsedLines.Current[7], out vParseSettleMM);
vWasSuccessful = double.TryParse(parsedLines.Current[8], out vParseOpen);
vWasSuccessful = int.TryParse(parsedLines.Current[6], out vParseBuy);
vWasSuccessful = int.TryParse(parsedLines.Current[10], out vParseSell);
//adding temp variabels to sum
vSettleMMSum += vParseSettleMM;
vOpenSum += vParseOpen;
vBuySum += vParseBuy;
vSellSum += vParseSell;
vMore = parsedLines.MoveNext();
}
//sets up when to break
while (vMore && vAccount == parsedLines.Current[vViewControl]);
//After each Break need to print out Account name and sums from above.
// Do printing here as part of the loop, at the very end of the loop code block.
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine(vAccount + " " + vSettleMMSum + " " + vOpenSum + " " + vBuySum + " " +
vSellSum);
//vWriteFile.Write(vAccount + "," + vSettleMMSum + "," + vOpenSum + "," + vBuySum + "," +
// vSellSum);
vWriteFile.WriteLine("{0},{1},{2},{3},{4}", vAccount, vSettleMMSum, vOpenSum, vBuySum, vSellSum);
//reset sums for next loop
vSettleMMSum = 0;
vOpenSum = 0;
vBuySum = 0;
vSellSum = 0;
}
}
}
}

Related

How to print stars depending on value of an array?

I recently make a program to calculate sum and avg of a given array. The program also want to print the histogram or stars pattern match with value of index.
Like this:
This is the code I wrote so far:
private void process_Click(object sender, EventArgs e)
{
string temp2 = null;
string temp3 = null;
float sum=0;
int countingNumber = 1;
string message;
int count = Convert.ToInt32(inputArray.Text);
int[] varray = new int[count];
for (int i = 0; i < count; i++)
//for (int j = 1; j <= count; j++)
{
varray[i] = Convert.ToInt32(Interaction.InputBox(message = "enter the value of array number " + countingNumber));
sum = sum+ varray[i];
temp += countingNumber + " "+varray[i] + Environment.NewLine;
temp2 += countingNumber + " " + varray[i] + " *" + Environment.NewLine;
box1.Text = Convert.ToString("Index Value" + Environment.NewLine + temp);
boxSum.Text = Convert.ToString(sum);
boxAvg.Text = Convert.ToString(sum/count);
countingNumber++;
}
for (int stars = 0; stars <= i; stars++)
{
temp3 = " ";
box2.Text = Convert.ToString("Element Value Histogram" + Environment.NewLine + temp2+temp3);
}
}
}
My code won't print the stars match with the value. Could anybody help me?
Try replacing this line:
temp2 += countingNumber + " " + varray[i] + " *" + Environment.NewLine;
with this line:
temp2 += countingNumber + " " + varray[i] + " " + new String('*', i) + Environment.NewLine;

how to calculate totals and minimum spanning trees using arrays

I'm working on a C# assignment in which i have to create a minimum spanning tree through the use of arrays. My code is made up of three arrays which track the nodes and whether or not they have been reached. I have to find the smallest total for all of the randomly generated links to be added up to visit all of the nodes. However, for some reason it is not quite working. The totals being produced are not correct and just wondered if anyone could help me work out why.I believe the error must be between the calculating of the total or how the minimum value is being decided or possible both however i am unsure.
So far i have tried changing the way it is calculated to involve a sum variable to store the values seperately. Ive attempted to add another if statement that would stop the min value from being anything above 98 ( the void value is 99) i have also tried to alter the earlier code to see if how i am testing the values in the SP array are the desired ones. still no results
int n = 5; //n = number of values
int m = 50; //m = max value in arra
int VoidValue = 99; // if i = j value = void value
int Total = 0; //Total value for spanning tree
int sum = 0; //Sum for total value for spanning tree
Random Rand = new Random(); //Create randomise value
int[,] c = new int[n + 1, n + 1]; //Cost array
int[] SP = new int[n + 1]; //Spanned array
int[,] AD = new int[n + 1, n + 1]; //Adjacency array
for (int i = 1; i <= n; i++)
{
SP[i] = 0;
for (int j = 1; j <= n; j++)
{
if (i == j)
{
c[i, j] = VoidValue; // give void spaces the value of 99
AD[i, j] = 0;
}
else
{
c[i, j] = Rand.Next(1, m); // Populate the array with randomised values
AD[i, j] = 0;
}
}
}
//Output all arrays to screen
Console.WriteLine("Cost Array: At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("c[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("c[" + i + "," + j + "] = " + c[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Spanned Array : At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Adjacency Array : At the beginning");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("A[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("A[" + i + "," + j + "] = " + AD[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
// Random Starting Point
int startPoint = Rand.Next(1, n + 1);
Console.WriteLine("Start at node " + startPoint);
SP[startPoint] = 1;
//Check the spanned array
Console.WriteLine("");
Console.WriteLine("Spanned Array : After the starting point has been chosen ");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
// Find minimum vallue link, repeatedly follow these links until spanned array is full
for (int p = 1; p < n; p++) // For every value of the spanned array
{
int MinValue = VoidValue, MinValuei = 0, MinValuej = 0; // declare variables
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++) // I and J are for both variables of the cost and adjacent array
if (i != j)
{
if (SP[i] == 1) //Spanned node
{
if (SP[j] == 0) //Unspanned node
{
if (c[i, j] < MinValue)
{
MinValue = c[i, j];
MinValuei = i;
MinValuej = j;
}
}
}
}
AD[MinValuei, MinValuej] = 1;
SP[MinValuej] = 1;
}
Console.WriteLine("");
Console.WriteLine("The min value is: " + MinValue);
Total = Total + MinValue;
Console.WriteLine("");
Console.WriteLine("The total is: " + Total);
}
//Finally output spanned and adjacent arrays
Console.WriteLine("");
Console.WriteLine("Spanned Array: After spanning tree");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
Console.Write("S[" + i + "] = " + SP[i].ToString("00") + " ");
Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Adjacency Array : After spanning tree");
Console.WriteLine("");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
if (i == j)
{
Console.Write("A[" + i + "," + j + "] = " + "- " + " ");
}
else
{
Console.Write("A[" + i + "," + j + "] = " + AD[i, j].ToString("00") + " ");
}
}
Console.WriteLine();
}
Console.ReadLine();
//Output total value for the spanning tree
Console.WriteLine("");
Console.WriteLine("The total value for the spanning tree: " + Total);
Console.WriteLine("");
Console.ReadLine();

Multithreading List AddRange

Issue is that TotalRows is about 71800 where the workList only returns 718 which is only the first result of the Task. I have the WaitAll there but it seems to finish as soon as the first task is done.
TotalRows = GetRowCount();
var lastRecord = 0;
List<tmpWBITEMALL> workList = new List<tmpWBITEMALL>();
for (int i = 0; i < 100; i++)
{
var tmpI = i;
gatherTmpTasks.Add(Task.Factory.StartNew(() =>
{
var context = new AS400_PIM5ContextDataContext();
context.CommandTimeout = 0;
int amount = (TotalRows / 100);
int tmplastRecord = lastRecord;
Interlocked.Add(ref lastRecord, amount);
Console.WriteLine("Getting rows " + tmplastRecord+ " to " + (tmplastRecord + amount));
var pagedResult = context.ExecuteQuery<tmpWBITEMALL>("SELECT * FROM (SELECT ROW_NUMBER() OVER ( ORDER BY Id ) AS RowNum, * from tmpWBITEMALL) AS RowConstrainedResult WHERE RowNum >= " + tmplastRecord+ " AND RowNum < " + amount + " ORDER BY RowNum");
lock (listLock)
workList.AddRange(pagedResult);
context.Dispose();
}));
}
Task.WaitAll(gatherTmpTasks.ToArray());
Console.WriteLine("total work: " + workList.Count + " tasks: " + gatherTmpTasks.Count);
So as reference gatherTmpTasks.Count returns 100 but workList.Count is only 718 where as listLock is just a static new object(). If didn't notice already I am using LINQ to SQL
Anyone have ideas why my list isn't the same size as TotalRows?
" AND RowNum < " + amount: amount is always 718, so you are asking the query to always return things between tmplastRecord and 718, NOT inbetween tmplastRecord and tmplastRecord + amount. I think you just need to change to " AND RowNum < " + (tmplastRecord + amount)
Wise man

How can i convert the string to int and count? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
public void Save(string path , string fileName , PictureBox pb)
{
int framesNumberX = 0;
int framesNumberY = 0;
string fn;
string t = Path.GetFileNameWithoutExtension(this.name);
if (File.Exists(path + "\\" + "DATABASE" + "\\" + fileName + "\\" + t + ".txt"))
{
try
{
string f = Path.Combine(path + "\\" + "DATABASE" + "\\" + t + "\\" + fileName);
File.Delete(f);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not delete file from disk. Original error: " + ex.Message);
}
fn = path + "\\" + "DATABASE" + "\\" + t + "\\" + fileName;
}
else
{
fn = path + "\\" + "DATABASE" + "\\" + fileName + "\\" + this.name + ".txt";
}
OptionsFile setting_file = new OptionsFile(fn);
setting_file.SetKey("File Name", fn);
setting_file.SetKey("Object Name", fileName);
setting_file.SetKey("Animation Name", this.name);
setting_file.SetKey("picturebox.Width", pb.Width.ToString());
setting_file.SetKey("picturebox.Height", pb.Height.ToString());
string[] xFrames = new string[wocl.Count];
string[] yFrames = new string[wocl.Count];
string X="";
string Y="";
for (int i = 0; i < wocl.Count; i++)
{
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
int c = Convert.ToInt32(X);
int d = Convert.ToInt32(Y);
framesNumberX += c;
framesNumberY += d;
for (int j = 0; j < wocl[i].Point_X.Count; j++)
{
xFrames[i] += string.Format("{0},", wocl[i].Point_X[j]);
yFrames[i] += string.Format("{0},", wocl[i].Point_Y[j]);
}
string tt = xFrames[i].Trim(",".ToCharArray());
string yy = yFrames[i].Trim(",".ToCharArray());
setting_file.SetKey(X, tt);
setting_file.SetKey(Y, yy);
}
setting_file.SetKey("Number Of Frames X", framesNumberX.ToString());
}
If im doing in the loop for example : FrameNumber +=; it will count me the number of frames for example 6. But i want to count how many times the frames of X showed up and how many frames of Y.
I tried ot it like this:
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
int c = Convert.ToInt32(X);
int d = Convert.ToInt32(Y);
framesNumberX += c;
framesNumberY += d;
But thats not working not a good way.
Maybe i need to make the counting of X and Y in the end after the variables tt and yy ?
I want to count how many times the loop did the variable tt and how many times it did the variable yy. Just puting int variable and make ++ will give me the overall frames i need to seperate them to X and Y. So if i have for example 6 frames so X will be 3 and Y will be 3.
Convert.Int32() isn't a Val() method, in other words, it won't take just the numbers from any string. When using Convert.Int32(), the entire string has to be numeric, for example:
// doesn't work
string x = "My string 123";
int y = Convert.Int32(x);
// does work
string x = "123";
int y = Convert.Int32(x);
If I understand correctly, you're trying to convert something to an int and count at the same time (here).
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
// blows up with an exception
int c = Convert.ToInt32(X);
int d = Convert.ToInt32(Y);
framesNumberX += c;
framesNumberY += d;
The above could better be written like:
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
framesNumberX++;
framesNumberY++;
// or (depending on what you need)
framesNumberX = i + 1;
framesNumberY = i + 1;
Or - Which would be even more clear; do your math operation first, then use the result in your string.Format() call;
framesNumberX = i + 1;
framesNumberY = i + 1;
X = string.Format("Frame_X_{0} ", framesNumberX);
Y = string.Format("Frame_Y_{0} ", framesNumberY);
However, framesNumberX and framesNumberY would be equal to eachother AND to the iterator i + 1. This is where I'm starting to lose the purpose of the variables. It would help if you could clarify in pseudo-code what exactly you're trying to accomplish:
public void MyMethod()
{
... code here
// trying to `your explanation`
... code here
// and here, I'm trying to `your explanation`
... code here
}
EDIT
for this code to work
X = string.Format("Frame_X_{0} ", i + 1);
Y = string.Format("Frame_Y_{0} ", i + 1);
int c = Convert.ToInt32(ExtractNumbers(X));//modfied code line
int d = Convert.ToInt32(ExtractNumbers(Y));//modfied code line
framesNumberX += c; framesNumberY += d;
you need to extract number something like this
static string ExtractNumbers( string expr )
{
return string.Join( null,System.Text.RegularExpressions.Regex.Split( expr, "[^\\d]" ) );
}
Prev Ans
Good way to do is
static void Main()
{
// Convert string to number.
string text = "123";
int num = -1;
if( int.TryParse (text,out num))
Console.WriteLine(num);
}
check that string is convertable or not

Why the line im writing to a text file inside the loop for is written to the text file so many times?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication_FileComparison
{
class Program
{
static void Main(string[] args)
{
//renameFiles();
duplicateFilesFinder();
}
public static string duplicateFilesFinder()
{
Console.WindowWidth = 107;
byte[] a, b;
StreamWriter sw;
string sf;
string[] images;
int x = 0;
int y = 0;
sw = new StreamWriter(#"d:\stream.txt");
sf = #"d:\test";
images = Directory.GetFiles(sf, "*.jpg");
for (x = 0; x < images.Length - 1; x++)
{
for (y = x + 1; y < images.Length; y++)
{
Console.Write("Working on file " + images[x] + " please wait\r");
if (!File.Exists(images[x]))
{
Console.Write("The file " + images[x] + " is not exist\r");
sw.WriteLine("The file " + images[x] + " is not exist");
}
else
{
if (File.Exists(images[y]))
{
a = File.ReadAllBytes(images[x]);
b = File.ReadAllBytes(images[y]);
if (a.Length == b.Length)
{
Console.WriteLine("File " + images[x] + " is the same size as" + " " + images[y]);
sw.WriteLine("File " + images[x] + " is the same size as" + " " + images[y]);
File.Delete(images[y]);
Console.WriteLine("File " + images[y] + " have been deleted");
sw.WriteLine("File " + images[y] + " have been deleted");
}
}
}
}
}
sw.Close();
Console.WriteLine(Environment.NewLine + "Process finished please press any key to continue");
Console.ReadKey();
return sf;
}
This is the are problem:
if (!File.Exists(images[x]))
{
Console.Write("The file " + images[x] + " is not exist\r");
sw.WriteLine("The file " + images[x] + " is not exist");
}
If i dont put \r on the console.Write and using Console.WriteLine without \r i see in the consol window this images[x] file many times!
Same the second line the sw.WriteLine in the text file i see it many times there.
I want just to see it once if the file not exist show it once.
Why does it show it so mant times ? And how ot fix it ?
Thanks.
That's because you are testing for the X file inside the Y loop. Put that test in the outer loop instead:
for (x = 0; x < images.Length - 1; x++) {
Console.Write("Working on file " + images[x] + " please wait\r");
if (!File.Exists(images[x])) {
Console.Write("The file " + images[x] + " is not exist\r");
sw.WriteLine("The file " + images[x] + " is not exist");
} else {
for (y = x + 1; y < images.Length; y++) {
...
The index for your inner loop is Y not X. So what you are currently doing is printing the element at index X, Y times within the inner loop - i.e. you are processing the element at X, Y times instead of once for the purposes of your output statements.
What you should do is move the block of code before the second loop. Checking that the file at X exists only once is enough, until X changes. So try:
Console.Write("Working on file " + images[x] + " please wait\r");
if (!File.Exists(images[x]))
{
Console.Write("The file " + images[x] + " is not exist\r");
sw.WriteLine("The file " + images[x] + " is not exist");
} else {
for (y = x + 1; y < images.Length; y++)
{
// Etc
}
}

Categories