Error while opening csv file in C# - c#

I'm stuck here while opening and reading csv file in c# program. Ive just started working upon ILNumerics to display 3D matrix graph, but the Exception rises with
"Could not find file 'C:\Users\asd\Documents\Visual Studio 2013\Projects\matrixgraph\martix\bin\Debug\stats.csv'."
Please help me out!
Below is the code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using ILNumerics;
using ILNumerics.Drawing;
using ILNumerics.Drawing.Plotting;
namespace martix
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ilPanel1_Load(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string path = #"C:\Users\asd\Documents\Visual Studio 2013\Projects\matrixgraph\martix\bin\Debug\stats.csv";
StreamReader sr = new StreamReader(File.Open(path, FileMode.Open));
string dataLines = string.Empty;
while (sr.Peek() != -1)
dataLines += sr.ReadLine().Replace(";", ",") + "\n";
sr.Close();
dataLines = dataLines.Trim('\n');
//Convert the data-string into an ILArray
ILArray<int> AN = ILMath.csvread<int>(dataLines);
//Create a new scene, which is the base for our graph
var scene = new ILScene();
using (ILScope.Enter())
{
//Convert all data points to float
ILArray<float> A = ILMath.tosingle(AN);
//Add a plot to the scene and configure it
scene.Add(new ILPlotCube
{
//Render in 3D
TwoDMode = false,
//Add 3 axes
Axes =
{
XAxis =
{
Label = { Text = "Price in $" },
GridMajor =
{
DashStyle = DashStyle.Dashed,
Color = Color.DarkGray,
Width = 1
}
},
YAxis =
{
Label = { Text = "Rating count" },
GridMajor =
{
DashStyle = DashStyle.Dashed,
Color = Color.DarkGray,
Width = 1
}
},
ZAxis =
{
Label = { Text = "Download count" }
}
},
//Add the data points
Children = {
new ILPoints {
Positions = A
},
},
//Set start rotation for 3D rendered graph
Rotation = Matrix4.Rotation(new Vector3(1, 1, 1), 0.5f)
});
}
//Add the scene to the ILPanel
ilPanel1.Scene = scene;
}
}
}

It may be the spaces you have in the path. Nevermind, you're using verbatim string.
Are you sure that path is accessible and is not a networked mapped path? Can you move your file temporarily? It really seems that you don't have access to that path.
Also you should try doing the following to pinpoint the issue:
System.IO.FileInfo fi = null;
try
{
fi = new System.IO.FileInfo(path);
}
catch (ArgumentException) {... }
catch (System.IO.PathTooLongException) {... }
catch (NotSupportedException) {... }
if (ReferenceEquals(fi, null))
{
...
// file name is not valid
}
else
{
...
// file name is valid... May check for existence by calling fi.Exists.
}
EDIT:
use System.IO.Directory.GetFiles to list the exact names of the files in that folder, it may be that the file name is different (stats.csv.csv) and window explorer is hiding the extension.

Got the solution while trying. I created the csv file programatically and this time it read the file.
Just added the few line before the path and modified the path.
StringBuilder csv = new StringBuilder();
csv.AppendLine("112,113,222");
string csvpath = #"C:\\stats\xyz.csv";
File.AppendAllText(csvpath,csv.ToString());
string path = #"C:\stats\xyz.csv";
And thats it. Anyways Thanks for helping :)

Related

C# Delete line from .txt extension with a changing filename

I am currently trying to make an .exe in c# that I can drag and drop a .txt file onto to remove lines of text that contain the keywords "CM" and/or "Filling". It must be able to overwrite the existing data so there are no new files created. The filename is different every time except for the extension. The data is tab delimited if that has any bearing. I'm aware that there are similar questions to this but I haven't managed to adapt them to suit my needs. Also, I'm very new to this and I've been trying for about a week with no luck.
if (args.Length == 0)
return; // return if no file was dragged onto exe
string text = File.ReadAllText("*.txt");
text = text.Replace("cm", "");
string path = Path.GetDirectoryName(args[0])
+ Path.DirectorySeparatorChar
+ Path.GetFileNameWithoutExtension(args[0])
+ "_unwrapped" + Path.GetExtension(args[0]);
File.WriteAllText("*.txt", text);
\\attempt 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
string concrete = "CM";
string line;
using (StreamReader reader = new StreamReader(#"C:\\Users\drocc_000\Desktop\1611AN24T99-041805221704.txt"))
{
using (StreamWriter writer = new StreamWriter(#"C:\\Users\drocc_000\Desktop\1611AN24T99-041805221704NEW.txt"))
{
while ((line = reader.ReadLine()) != null)
{
// if (String.Compare(line, yourName) == 0)
// continue;
writer.WriteLine(line.Replace(concrete, ""));
}
}
}
\\attempt 2
Thanks for your time.
Regards,
Danny
You can create a console application with the code below and then drag and drop your text file into the .exe file without opening it.
class Program
{
static void Main(string[] args)
{
if (args.Length > 0 && File.Exists(args[0]))
{
string path = args[0];
EditFile(new List<string>() { "CM", "Filling" }, path);
}
Console.Read();
}
public static void EditFile(List<string> keyWords, string filename)
{
List<string> lines = new List<string>();
using (StreamReader sr = new StreamReader(filename))
{
while (sr.Peek() >= 0)
{
lines.Add(sr.ReadLine());
}
sr.Close();
}
int removedLinesCount = 0;
bool writeline;
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (var line in lines)
{
writeline = true;
foreach (var str in keyWords)
{
if (line.Contains(str))
{
writeline = false;
removedLinesCount++;
break;
}
}
if (writeline)
sw.WriteLine(line);
}
Console.WriteLine(removedLinesCount + " lines removed from the file " + filename);
sw.Close();
}
}
}
Something like this?
using System;
using System.IO;
using System.Linq;
namespace ConsoleApp1
{
internal static class Program
{
private static void Main(string[] args)
{
try
{
// Get the filename from the applications arguments
string filename = args[0];
// Read in all lines in the file.
var linesInFile = File.ReadLines(filename);
// Filter out the lines we don't need.
var linesToKeep = linesInFile.Where(line => !line.Contains("CM") && !line.Contains("Filling")).ToArray();
// Overwrite the file.
File.WriteAllLines(filename, linesToKeep);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

How to create and save an XML file containing complete hierarchy of files and folders for a specified folder?

this is my first post here on the site :)
So basically I need a gui application that can create and save XML file containing complete hierarchy of files and folders for a specified folder.
1.Each folder should be qualified with: Folder name, Folder size (bytes) and Number of files.
2.Each file should be qualified with: File name, File size (bytes), File creation, File last access time, File last modified time.
After the XML file is created the application needs to display the entire folder hierarchy tree (by using the TreeView class).
Can anyone provide help and answer? Thanks!
Try following code. Fully tested. Start with small Directory. Very large folders may take time. I updated code to speed up loading the treeview.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;
namespace WindowsFormsApplication29
{
public partial class Form1 : Form
{
XDocument doc = null;
public Form1()
{
InitializeComponent();
folderBrowserDialog1.SelectedPath = #"c:\temp";
}
private void buttonBrowseForFolder_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
textBoxFolderName.Text = folderBrowserDialog1.SelectedPath;
}
private void buttonCreateXml_Click(object sender, EventArgs e)
{
if(Directory.Exists(textBoxFolderName.Text))
{
string header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Directory></Directory> ";
doc = XDocument.Parse(header);
XElement root = doc.Root;
CreateXmlRecursive(textBoxFolderName.Text, root);
}
}
private float CreateXmlRecursive(string folder, XElement folderElement)
{
folderElement.SetValue(folder);
DirectoryInfo dInfo = new DirectoryInfo(folder);
int numberOfFiles = 0;
float size = 0.0f;
foreach(FileInfo fInfo in dInfo.GetFiles())
{
try
{
float fSize = fInfo.Length;
size += fSize;
folderElement.Add(new XElement("File", new object[] {
new XAttribute("size",fSize),
new XAttribute("creationDate", fInfo.CreationTime.ToShortDateString()),
new XAttribute("lastAccessDate", fInfo.LastAccessTime.ToShortDateString()),
new XAttribute("lastModifiedDate", fInfo.LastWriteTime.ToShortDateString()),
fInfo.Name
}));
numberOfFiles += 1;
}
catch(Exception e)
{
Console.WriteLine("Error : CAnnot Access File '{0}'", fInfo.Name);
}
}
foreach(string subFolder in Directory.GetDirectories(folder))
{
XElement childDirectory = new XElement("Directory");
folderElement.Add(childDirectory);
float dSize = CreateXmlRecursive(subFolder, childDirectory);
size += dSize;
}
folderElement.Add(new XAttribute[] {
new XAttribute("size", size),
new XAttribute("numberOfFiles", numberOfFiles)
});
return size;
}
private void buttonCreateTree_Click(object sender, EventArgs e)
{
if (doc != null)
{
TreeNode rootNode = new TreeNode(doc.Root.FirstNode.ToString());
AddNode(doc.Root, rootNode);
treeView1.Nodes.Add(rootNode);
treeView1.ExpandAll();
}
}
private void AddNode(XElement xElement, TreeNode inTreeNode)
{
// An element. Display element name + attribute names & values.
foreach (var att in xElement.Attributes())
{
inTreeNode.Text = inTreeNode.Text + " " + att.Name.LocalName + ": " + att.Value;
}
// Add children
foreach (XElement childElement in xElement.Elements())
{
TreeNode tNode = inTreeNode.Nodes[inTreeNode.Nodes.Add(new TreeNode(childElement.Value))];
AddNode(childElement, tNode);
}
}
}
}
Your question is - can u do my application for me - but anyway.
I will give you some hints to get started with your Project.
First of all - Check out MVVM here. This will help you - to handle WPF.
1. Pick the starting folder
Then you will need a FolderPicker to start your Search
public static string PickFolder()
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
string folder = string.Empty;
switch (result)
{
case System.Windows.Forms.DialogResult.OK: return dialog.SelectedPath;
case System.Windows.Forms.DialogResult.Cancel: return string.Empty;
default: return string.Empty;
}
}
U will need the System.Windows.Forms Assembly for this. (Project -> Add reference -> Assembly)
2. folders and files
Then you want to itterate through all folders.
Check out System.IO.Directory here
3. file information
Check out System.IO.File here - this will give you some file data and to get the file size check this out

Removing a row from a csv file when it is selected from a comboBox and a button pressed

I recently asked about a piece of code to hold data for my trading cards. I have a file that contains the overall list of the cards in a CSV file. I was wondering if there was any way to remove a row from the CSV file when the card number is selected and the submit button pressed. The code I currently have is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text, lblCardTypeFinal.Text);
Global.card.Add(card);
File.AppendAllLines(file, new[] { card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter + card.CardType });
MessageBox.Show("Card Added");
}
}
}
So I want the row to be removed from the 'loblist.csv' and added to the LOB file (which it is currently doing). Thanks
This should work (untested). Unfortunately, there's no classes/methods available in .Net (AFAIK) for in-place editing of text files (it makes sense when you think about it I guess). Disclaimer - there are much cleaner ways to do what you're aiming for here functionality-wise, including the approach described by Plutonix above:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace YuGiOh_Card_List
{
public partial class frmAddLOB : Form
{
List<string> cardNo = new List<string>();
List<string> cardName = new List<string>();
List<string> cardRarity = new List<string>();
List<string> cardType = new List<string>();
List<string> Lines = new List<string>();
public frmAddLOB()
{
InitializeComponent();
StreamReader reader = File.OpenText("..\\Debug\\lobList.csv");
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Lines.Add(line);
cardNo.Add(values[0]);
cardName.Add(values[1]);
cardRarity.Add(values[2]);
cardType.Add(values[3]);
cboCardNo.Items.Add(values[0]);
}
reader.Close();
}
private void cboCardNo_SelectedIndexChanged(object sender, EventArgs e)
{
lblCardNoFinal.Text = cardNo[cboCardNo.SelectedIndex];
lblCardNameFinal.Text = cardName[cboCardNo.SelectedIndex];
lblCardRarityFinal.Text = cardRarity[cboCardNo.SelectedIndex];
lblCardTypeFinal.Text = cardType[cboCardNo.SelectedIndex];
}
private void btnAdd_Click(object sender, EventArgs e)
{
string file = ("..\\Debug\\LOB.csv");
string delimiter = ",";
var card = new Card(lblCardNoFinal.Text, lblCardNameFinal.Text, lblCardRarityFinal.Text,
lblCardTypeFinal.Text);
Global.card.Add(card);
var newLine = card.CardNo + delimiter + card.CardName + delimiter + card.CardRarity + delimiter +
card.CardType;
File.AppendAllLines(file,
new string [] {newLine});
if (Lines.Contains(newLine))
{
Lines.Remove(newLine);
File.WriteAllLines("..\\Debug\\lobList.csv", Lines);
}
MessageBox.Show("Card Added");
}
}
}

C# Second text box filling out with random names

this is my code and I also have a snippet in the link below of what my program looks like when run. My problem is with the second text box and that it is filling out with random gibberish. My first text box is working perfectly it is picking a random first name from my text file and putting it into the text box. I dont understand what my second text file isnt doing the same'?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
{
Random r = new Random();
int currentLinefirst = 1;
string pick = null;
foreach (string line in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\First Names.txt"))
{
if (r.Next(currentLinefirst) == 0)
{
pick = line;
}
++currentLinefirst;
}
textBox1.Text = pick;
}
Random n = new Random();
int currentLinelast = 1;
string pick2 = null;
foreach (string line1 in File.ReadLines("C:\\Users\\Admin\\Desktop\\C# Programs\\WindowsFormsApplication5\\WindowsFormsApplication5\\Last Names.txt"))
{
if (n.Next(currentLinelast) == 0)
{
pick2 = line1;
}
++currentLinelast;
}
textBox2.Text = pick2;
}
}
}
i am getting this output of random numbers in textbox
It is probably because your second file contains a line with multiple names. When you call File.ReadLines, it will return an array of string on each line
Try separating you last names with line feeds.
To save the text to a text file use
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\Users\Admin\Desktop\test.txt", true))
{
file.WriteLine("First Name: {0} Last Name: {1}", textBox1.Text, textBox2.Text);
}
{0} and {1} are placeholders
if the file is does not exist it will create a new file to the given path and if the file already exists then it will add new entry to the file.
You can try this:
string firstname = textBox1.Text;
string lastname = textBox2.Text;
Byte[] info = new UTF8Encoding(true).GetBytes(firstname + lastname);
string FilePath = yourpath + DateTime.Now.ToString("dd-MMM-yyyy") + ".txt";
using (FileStream fs = File.Create(FilePath))
{fs.Write(info, 0, info.Length);}

power point printing problem using C#

I'm using the COM objects from Office 2007 to handle and print ms-office files. I don't have any problems with word and excel documents, but i just can't print Power Point docs.
the code bellow just opens the file send a job to the printer but nothing gets printed
what am i doing wrong? =(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Main
{
class PrintPPoint
{
public static void PrintPPointDocument(string filename, int copies, string range)
{
Microsoft.Office.Interop.PowerPoint.Presentation work = null;
Microsoft.Office.Interop.PowerPoint.Application app = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
Microsoft.Office.Interop.PowerPoint.Presentations presprint = app.Presentations;
//app.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
work = presprint.Open(filename, Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoTriState.msoFalse);
work.PrintOptions.PrintInBackground = 0;
work.PrintOptions.ActivePrinter = app.ActivePrinter;
if (range.Equals("0"))
{
work.PrintOut(0, 1, app.ActivePrinter, copies, Microsoft.Office.Core.MsoTriState.msoFalse);
}
else
{
string[] toprintsheet = range.Split(new char[] { ',' });
foreach (string aux in toprintsheet)
{
work.PrintOptions.PrintInBackground = 0;
work.PrintOptions.ActivePrinter = app.ActivePrinter;
if (aux.Contains("-"))
{
int from = 0, to = 0;
string[] SplitRange = aux.Split(new char[] { '-' });
from = Convert.ToInt16(SplitRange[0]);
to = Convert.ToInt16(SplitRange[1]);
work.PrintOut(from, to, app.ActivePrinter, 1, Microsoft.Office.Core.MsoTriState.msoFalse);
}
else
{
work.PrintOut(Convert.ToInt16(aux), Convert.ToInt16(aux), app.ActivePrinter, copies, Microsoft.Office.Core.MsoTriState.msoFalse);
}
}
}
work.Close();
app.Quit();
}
}
}
I just needed to set
PrintOptions.PrintInBackground = Microsoft.Office.Core.MsoTriState.msoFalse
That lets the jobs complete.
I can't tell you but I bet you can easily find out yourself...
I assume that this is an application that interacts with the desktop and not some background service.
I would step through the code slowly and see if it works.. (for both app.visible = true and not.) If it works, it may be a race between ppoint printing functionality and ppoint closing the document/quiting. (Even though you've turned off background printing) and you have check for that...
Good luck

Categories