Save Opened Text File to Original Location - c#

I am creating an application that will allow me to open a .txt file and edit the values (weight=60, height =50, etc) in a DataGridView. My issue is that I am able to upload the .txt file using OpenFileDialog but am unable to write over and save it in it's previous location.
For clarification, here is my method to upload text files:
private void btnUpload_Click(object sender, EventArgs e)
{
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "C:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(openFileDialog1.FileName);
string line;
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split('=');
paramList.Add(new Parameter(words[0], words[1]));
}
BindGrid();
}
}
And what I've tried to save the file:
public void WriteToTextFile(DataGridView dgvParam)
{
String file_name = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
using (StreamWriter objWriter = new StreamWriter(openFileDialog1.FileName))
{
for (Int32 row = 0; row < dgvParam.Rows.Count - 1; row++)
{
StringBuilder sb = new StringBuilder();
for (Int32 col = 0; col < dgvParam.Rows[row].Cells.Count; col++)
{
if (!String.IsNullOrEmpty(sb.ToString()))
sb.Append("="); //any delimiter you choose
sb.Append(dgvParam.Rows[row].Cells[col].Value.ToString().ToUpper());
}
objWriter.WriteLine(sb.ToString());
}
}
It says it is openFileDialog is currently in use and it cannot reach it! Any suggestions or recommendations would be really appreciated!

You need to dispose your reader variable.
You should get rid of the first using statement entirely and wrap that in a using statement instead.

Related

How can I add 2 cells in a CSV file in WPF?

I use the OpenFileDialog in my WPF program to give the user the option to select a .csv file and read it into the program. Now I have the path and everything from the file that the user wants and now I want to add 2 more cells to the Excel file after a button click. How should I change it so that as soon as the button is pressed, 2 columns and cells are added to the previously imported Excel file. Here is my OpenFileDialog how I get the file OpenFileDialog::
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
openFileDialog.Title = "CVS Datei Auswählen zum Konvertieren";
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
{
tbxFiles.Items.Add(System.IO.Path.GetFileName(filename));
string temp;
var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
temp = streamReader.ReadToEnd();
test = temp;
}
}
}
SaveFileDialog:
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
List<String> liste = new List<String>();
// test = test + "Hallo;";
//File.WriteAllText(dialog.FileName, test);
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(test);
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{""},{""}";
}
counter++;
}
file.Close();
}
In my "test" string I have now read in what is in the cvs file via streamreader. This is what the cvs Header looks like:
Picture 1
and so how i want it look like after my C# change:
Picture2
tbxFiles = my TextBox where the path of the selected file is shown.
So how can I add additional Excel columns with associated cells to the imported Excel file in Code Behind 2?
There you go:
....
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{value1},{value2}";
}
counter++;
}
...

How to link users file selection to a StringSplit

I'm trying to get the users chosen file to split into an array which is separated by , and /t.
The user can choose a file at the top of the code but how do I get their choice to split into an array lower down when they press the ValidateButton
The text file or ordered in this way
info,info,info,
info,info,info,
info,info,info,
If I can get them into an array then I can easily organises the data.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\"; // Start in C: drive
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.DefaultExt = "txt"; // Extension of file is txt
openFileDialog1.Filter = "Text|*.txt||*.*"; //Only text files
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileNameBox.Text = openFileDialog1.FileName; // Chosen file name is displayed in text box
var fileStream = openFileDialog1.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
var fileContent = reader.ReadToEnd();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
//This is the file path the user has chosen
}
public void ValidateButton_Click(object sender, EventArgs e)
{
//Call Multi line text box
//Call PROGRESS BAR_
int counter = 0;
string lines;
string Patient = lines;
string[] split = Patient.Split(new Char[] { ',', '\t' });
foreach (string s in split)
if (s.Trim() != "")
Console.WriteLine(s);
{
Console.WriteLine(lines);
counter++;
}
Console.WriteLine("There were {0} records.", counter);
Console.ReadKey();
}
List<string> temp = new List<string>();
string[] finalArray;
using (StreamReader reader = new StreamReader(fileStream))
{
// We read the file then we split it.
string lines = reader.ReadToEnd();
string[] splittedArray = lines.Split(',');
// We will check here if any of the strings is empty (or just whitespace).
foreach (string currentString in splittedArray)
{
if (currentString.Trim() != "")
{
// If the string is not empty then we add to our temporary list.
temp.Add(currentString);
}
}
// We have our splitted strings in temp List.
// If you need an array instead of List, you can use ToArray().
finalArray = temp.ToArray();
}

Importing file to array

I want the user to be able to chose a text file written in a certain way (1 number per line) and then have the file converted into an array. I have bits and pieces of it working but I cant get it to all work at the same time. Any help would be appreciated.
private void Load_Button_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
List<int> list = new List<int>();
string fileName = "";
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = "TXT File|*.txt";
//ofd.Title = "Open File";
// if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
// {
File_Label.Text = "C:/Users/Neilan/Desktop/sample.txt";
//fileName = "#" + ofd.SafeFileName;
//MessageBox.Show(ofd.FileName);
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Neilan\Desktop\sample.txt");
while ((line = file.ReadLine()) != null)
{
Unsorted_Box.Text += line + ", ";
//list.Add(int.Parse(fileName));
counter++;
}
dataArray = list.ToArray();
// }
}
You can do this.
var numberarray = File.ReadAllLines("stringpath").Select(int.Parse).ToArray();
Looking at your code, I guess you want to show these values in comma separated format to user. You can achieve this with following code snippet.
Unsorted_Box.Text = String.Join(",", numberarray.ToArray());
Hope this helps !
This problem can be solved by one line
var resultArray = Array.ConvertAll(System.IO.File.ReadAllLines("filename.type"), str => int.Parse(str));
Instead of "filename.type" you can put something like File_Label.Text

How to read numbers in a .txt file to an integer array?

I have a file that I need to save as an array. I am trying to convert a text file to an integer array using StreamReader. I just am unsure as to what to put in the for loop at the end of the code.
This is what I have so far:
//Global Variables
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
OpenFileDialog fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
//open file to read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
int[] OriginalArray;
for (int i = 0; i < Records; i++)
{
//add code here
}
}
The .txt file is:
5
6
7
9
10
2
PS I am a beginner, so my coding skills are very basic!
UPDATE: I have previous experience using Line.Split and then mapping file to arrays but obviously that does not apply here, so what do I do now?
//as continued for above code
for (int i = 0; i < Records; i++)
{
int Line = int.Parse(sr.ReadLine());
OriginalArray = int.Parse(Line.Split(';')); //get error here
Original[i] = OriginalArray[0];
}
You should just be able to use similar code to what you had above it:
OriginalArray[i] = Convert.ToInt32(sr.ReadLine());
Every time the sr.ReadLine is called it increments the data pointer by 1 line, hence iterating through the array in the text file.
try this
OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
StreamReader reader = new StreamReader(fd.OpenFile());
var list = new List<int>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
int value = 0;
if (!string.IsNullOrWhiteSpace(line) && int.TryParse(line, out value))
list.Add(value);
}
MessageBox.Show(list.Aggregate("", (x, y) => (string.IsNullOrWhiteSpace(x) ? "" : x + ", ") + y.ToString()));
}
You can read the entire file into a string array, then parse (checking the integrity of each one).
Something like:
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
var fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
var file = fd.FileName;
try
{
var ints = new List<int>();
var data = File.ReadAllLines(file);
foreach (var datum in data)
{
int value;
if (Int32.TryParse(datum, out value))
{
ints.Add(value);
}
}
Original = ints.ToArray();
}
catch (IOException)
{
// blah, error
}
}
}
Another way to do it if you'd like to read to the end of the file and you don't know how long it is with a while loop:
String line = String.Empty;
int i=0;
while((line = sr.ReadLine()) != null)
{
yourArray[i] = Convert.ToInt32(line);
i++;
//but if you only want to write to the file w/o any other operation
//you could just write w/o conversion or storing into an array
sw.WriteLine(line);
//or sw.Write(line + " "); if you'd like to have it in one row
}
//using linq & anonymous methods (via lambda)
string[] records = File.ReadAllLines(file);
int[] unsorted = Array.ConvertAll<string, int>(records, new Converter<string, int>(i => int.Parse(i)));

Can I programatically copy my html selection

I have a html document that after being parsed contains only formatted text.I was wondering if it is possible to get its text like I would do if I was mouse-selecting it + copy + paste in new Text Document?
I know that this is possible in Microsoft.Office.Interop where I have .ActiveSelection property that selects the content of the open Word.
I need to find a way to load the html somehowe(maybe in a browser object) and then copy all of its content and assign it to a string.
var doc = new HtmlAgilityPack.HtmlDocument();
var documetText = File.ReadAllText(myhtmlfile.html, Encoding.GetEncoding(1251));
documetText = this.PerformSomeChangesOverDocument(documetText);
doc.LoadHtml(documetText);
var stringWriter = new StringWriter();
AgilityPackEntities.AgilityPack.ConvertTo(doc.DocumentNode, stringWriter);
stringWriter.Flush();
var titleNode = doc.DocumentNode.SelectNodes("//title");
if (titleNode != null)
{
var titleToBeRemoved = titleNode[0].InnerText;
document.DocumentContent = stringWriter.ToString().Replace(titleToBeRemoved, string.Empty);
}
else
{
document.DocumentContent = stringWriter.ToString();
}
and then I return the document object.The problem is that the string is not always formatted as I want it to be
You should be able to just use StreamReader and as you read each line just write it out using StreamWriter
Something like this will readuntil the end of your file and save it to a new one. If you need to do extra logic in the file I have a comment inserted to let you know where to do all that.
private void button4_Click(object sender, EventArgs e)
{
System.IO.StreamWriter writer = new System.IO.StreamWriter("C:\\XXX\\XXX\\XXX\\test2.html");
String line;
using (System.IO.StreamReader reader = new System.IO.StreamReader("C:\\XXX\\XXX\\XXX\\test.html"))
{
//Do until the end
while ((line = reader.ReadLine()) != null) {
//You can insert extra logic here if you need to omit lines or change them
writer.WriteLine(line);
}
//All done, close the reader
reader.Close();
}
//Flush and close the writer
writer.Flush();
writer.Close();
}
You can also save it to a string then just do whatever you want to with it. You can use new lines to keep the same format.
EDIT The below will tke into account your tags
private void button4_Click(object sender, EventArgs e)
{
String line;
String filetext = null;
int count = 0;
using (System.IO.StreamReader reader = new System.IO.StreamReader("C:\\XXXX\\XXXX\\XXXX\\test.html"))
{
while ((line = reader.ReadLine()) != null) {
if (count == 0) {
//No newline since its start
if (line.StartsWith("<")) {
//skip this it is formatted stuff
}
else {
filetext = filetext + line;
}
}
else {
if (line.StartsWith("<"))
{
//skip this it is formatted stuff
}
else
{
filetext = filetext + "\n" + line;
}
}
count++;
}
Trace.WriteLine(filetext);
reader.Close();
}
}

Categories

Resources