How to send CheckedListBox selection into textfile? - c#

I'm trying to code on my own for the first time, and decided to make a music player on Winforms.
I have a CheckedListBox that is already populated with the names of songs in a folder.
When I click a button, it's supposed to send the names of my selected songs into a .txt file for further manipulation, before closing the form.
For simplification, I'm just going with 1 selected song first.
private void selectbtn_Click(object sender, EventArgs e)
{
selectedSongs = checkedListBox1.CheckedItems.ToString();
songRecord.writeRecord(selectedSongs); //i initialised my streamreader/streamwriter class and called it songRecord
this.Close();
}
in my streamreader/writer class, this is what I have
class DataRecord
{
public void writeRecord(string line)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(#"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);
}
catch (FileNotFoundException)
{
Console.WriteLine("Error: File not found.");
}
catch (IOException)
{
Console.WriteLine("Error: IO");
}
catch(Exception)
{
throw;
}
finally
{
if (sw != null)
sw.Close();
}
}
public void readRecord()
{
StreamReader sr = null;
string myInputline;
try
{
sr = new StreamReader(#"C:\Users\Me\Desktop\JAM_MACHINE\record.txt");
while ((myInputline = sr.ReadLine()) != null) ; //readline reads whole line
Console.WriteLine(myInputline);
}
catch (FileNotFoundException)
{
Console.WriteLine("Error: File not found");
}
catch(IOException)
{
Console.WriteLine("Error: IO");
}
catch (Exception)
{
throw;
}
finally
{
if (sr != null)
sr.Close();
}
}
}
When I run it, the .txt file doesn't show my selection. It only shows:
System.Windows.Forms.CheckedListBox+CheckedItemCollection
What went wrong?

Iterate through the CheckedItems Collection and collect each item inside a string array. I assume you fill the checkedListBox with strings
private void selectbtn_Click(object sender, EventArgs e)
{
string[] checkedtitles = new string[checkedListBox1.CheckedItems.Count];
for (int ii = 0; ii < checkedListBox1.CheckedItems.Count; ii++)
{
checkedtitles[ii] = checkedListBox1.CheckedItems[ii].ToString();
}
string selectedSongs = String.Join(Environment.NewLine, checkedtitles);
songRecord.writeRecord(selectedSongs);
this.Close();
}

Related

(solved)IO exception The process cannot access the file because it is being used by another process

I'm trying to delete a line from a txt file with my program, but the program has the text file open so I can't. What do I do?
private void btnDeleteTransaction_Click(object sender, EventArgs e)
{
string line = null;
string delete = txtDeleteTransId.Text;
using (reader = new StreamReader(txtFilePath.Text))
{
try {
using (writer = new StreamWriter(txtFilePath.Text, true))
{
while ((line = reader.ReadLine()) != null)
{
if (String.Compare(line + "|", delete) == 0)
continue;
writer.WriteLine(line);
}
}
}
catch (Exception ex)
{
txtMessages.Text = "exception deleting transaction: " + ex.Message;
}
}
}
Figured it out below.
I'm dumb and was trying to write from the reader which you can't do. Here is my working code if anyone is as new as me.
private void btnDeleteTransaction_Click(object sender, EventArgs e)
{
List<string> records = new List<string>();
found = false;
using (reader = new StreamReader(txtFilePath.Text))
{
while (!reader.EndOfStream)
{
record = reader.ReadLine();
if (record.StartsWith(txtDeleteTransId.Text + "|"))
{
found = true;
}
else
{
records.Add(record);
}
}
if (!found)
{
txtMessages.Text = "Record ID was not found";
return;
}
}
try
{
using (writer = new StreamWriter(txtFilePath.Text, false))
{
foreach (var item in records)
{
writer.WriteLine(item);
}
}
txtMessages.Text = "Record deleted";
}
catch (Exception ex)
{
txtMessages.Text = "exception deleting record: " + ex.Message;
}
}
```

My function inserts data into the DB at times and doesn't at times

I'm developing a web form where I wish to upload a document related to a particular user into a folder and make a respective entry for the same in MySql server database. Now whenever I submit my details of my document, it uploads the document just fine but at times it skips the entry into the data base.
Code Segment 1
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
String path = Server.MapPath("~/AdminUploads/");
if (FileUpload1.HasFile)
{
Response.Write(FileUpload1.FileName);
try
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
DOCUPLOADED doc = new DOCUPLOADED();
doc.DOCTYPE = Int32.Parse(DropDownList2.SelectedValue);
doc.DOCID = TextBox4.Text;
doc.FILEPATH = path + FileUpload1.FileName;
doc.FORUSER = Int64.Parse(TextBox5.Text);
doc.FILENAME = TextBox6.Text;
uploaddoc ud = new uploaddoc(doc);
if (ud.upload())
{
Response.Write("<script>alert('Addition succesfull');<script>");
}
else
{
Response.Write("<script>alert('Fatal error : addition unsuccesfull');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('Error : File was not uploaded ');</script>");
}
}
Code Segment 2
public class uploaddoc
{
private DOCUPLOADED doc;
public uploaddoc(DOCUPLOADED doc)
{
this.doc = doc;
}
public bool upload()
{
if (doc != null)
{
dbcfDataContext dc = new dbcfDataContext();
dc.DOCUPLOADEDs.InsertOnSubmit(doc);
try
{
dc.SubmitChanges();
}
catch (Exception ex)
{
//
}
return true;
}
else
return false;
}
}
ID is supposed to be autoincremented, you can see 1-6 are absent,so are 9 10 etc.
dbcfdatacontext is the connection to database done by creating a dbml file and dragging the tables on to it.
I have fixed your code:
public class uploaddoc
{
private DOCUPLOADED doc;
public uploaddoc(DOCUPLOADED doc)
{
this.doc = doc;
}
public bool upload()
{
if (doc != null)
{
dbcfDataContext dc = new dbcfDataContext();
dc.DOCUPLOADEDs.InsertOnSubmit(doc);
//try
//{
dc.SubmitChanges();
//}
//catch (Exception ex)
//{
//
//}
return true;
}
else
return false;
}
}
But in all seriousness, empty catch blocks are the equivalent of shooting yourself in the foot. Don't do that.

How to add all the lines in one go

So I have this piece of code to add items from a text file into a combobox for an assignment. How would I go about adding all of the items in the text file altogether instead of one by one like I'm doing now.
private void Form1_Load(object sender, EventArgs e)
{
TextReader tr;
try
{
cboCity.Items.Clear();
tr = File.OpenText("C:\\Users\\Alexander\\Desktop\\CPI Institute\\CPR\\Debugging\\cities.txt");
for (int counter = 4; counter < 5; counter++)
{
cboCity.Items.Add(tr.ReadLine());
cboCity.Items.Add(tr.ReadLine());
cboCity.Items.Add(tr.ReadLine());
cboCity.Items.Add(tr.ReadLine());
tr.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error opening cities file", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You may use
cboCity.Items.AddRange(File.ReadAllLines("C:\\Users\\Alexander\\Desktop\\CPI Institute\\CPR\\Debugging\\cities.txt"));
to do that in one line.
everytime you call ReadLine method, it will proceed to next line, so the purpose of your loop is gone.
Do something like this,
string line;
StreamReader file = new System.IO.StreamReader("C:\\Users\\Alexander\\Desktop\\CPI Institute\\CPR\\Debugging\\cities.txt");
while((line = file.ReadLine()) != null)
{
cboCity.Items.Add(line);
}
file.Close();
Use Items.AddRange():
cboCity.Items.AddRange(new string[] { tr.ReadLine(), tr.ReadLine(), tr.ReadLine(), tr.ReadLine() });

File in Use while trying to Clear Text File

In my program I am loading a text files information into a rich text box. When the user clicks the clear button I want the files contents to be empty and display it again on the rich text box. However when I try to clear an error pops up that the file is already in use.
I am not sure of of what is going on with this, I have a suspicion it has to do with closing the stream reader or creating a new one. Either way I am not quite sure.
Does anyone have any thoughts of what is going on with this?
Code:
namespace FileLocationAutomation
{
public partial class ViewLog : Form
{
public ViewLog()
{
InitializeComponent();
}
#region Variables
string str = "";
#endregion
#region Ok Button
private void btnOK_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region Form Load
private void ViewLog_Load(object sender, EventArgs e)
{
//catch any exception
try
{
//load the log thats kept on the users machine into the rich text object
StreamReader read = new StreamReader(GlobalVars.strLogPath);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
#region Clear Log
//clear the log file and display it on the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
}
}
The problem is that you try to write to the file to clear it while still holding it open. The simplest change is to move the call to File.WriteAllText(GlobalVars.strLogPath, String.Empty); to after where you close the file, as follows:
#region Clear Log
//clear the log file and display it on the rich text box
private void btnClear_Click(object sender, EventArgs e)
{
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
A better change would probably to use the static read method, since you're reading the whole file in one go there's no need to use the StreamReader.
private void btnClear_Click(object sender, EventArgs e)
{
try
{
rtxtView.Text = File.ReadAllText(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The problem is strictly here:
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
Make it look like this:
try
{
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
StreamReader read = new StreamReader(GlobalVars.strLogPath);
str = read.ReadToEnd();
rtxtView.Text = str;
read.Close();
}
Or since reading a blank file back is useless, do it like this:
try
{
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
rtxtView.Text = String.Empty;
}
enclose the StreamReader declaration in using block {}to make sure that it gets disposed.
Try This:
using(StreamReader read = new StreamReader(GlobalVars.strLogPath))
{
str = read.ReadToEnd();
rtxtView.Text = str;
}
OR
rtxtView.Text = File.ReadAllText(GlobalVars.strLogPath);
You may change the order.
try
{
StreamReader read = new StreamReader(GlobalVars.strLogPath);
File.WriteAllText(GlobalVars.strLogPath, String.Empty);
str = read.ReadToEnd();
// close the stream first.
read.Close();
rtxtView.Text = str;
}

StreamReader Multiple lines

I am trying to figure out how to read multiple lines whith StreamReader. I have a text file with a list of commands inside it that I need to read from. My code works, however it will only read the first line. This causes me to have to move all my commands to a single line with a space between them. This is not a very tidy way of doing this seeing as I need to leave comments next to the commands. Example: CONNECT: "Connects to given IP."
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
if (e.KeyCode == Keys.Enter)
{
// Read the file and display it line by line.
StreamReader file = new StreamReader("C:\\Users\\Home\\Desktop\\commands.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(ConsoleEnter.Text))
{
COMBOX.Items.Add(ConsoleEnter.Text);
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
else
{
COMBOX.Items.Add("Invalid Command");
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
}
}
This is what am using in one of my app and its working fine hope it'll help you out.......
if (TxtPath.Text != string.Empty)
{
StreamReader srr = new StreamReader(TxtPath.Text);
try
{
ss = srr.ReadToEnd().Split('\n');
MessageBox.Show("File Successfully Loded in Memory \n" + TxtPath.Text, "System Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
throw new Exception("File are not readable or write protacted");
}
LblLineCount.Text = ss.Count().ToString();
}
else
{
MessageBox.Show("Please Browse any Log File 1st", "System Manager", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
you can also trim the
.Split('\n')
to take all data in single line, i can't try it right now but if check it will get u out of stuck...........
u should empty the variable after the loop, not inside the loop
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
if (e.KeyCode == Keys.Enter)
{
// Read the file and display it line by line.
StreamReader file = new StreamReader("C:\\Users\\Home\\Desktop\\commands.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(ConsoleEnter.Text))
{
COMBOX.Items.Add(ConsoleEnter.Text);
}
else
{
COMBOX.Items.Add("Invalid Command");
}
}
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
public void ConsoleEnter_KeyDown(object sender, KeyEventArgs e)
{
string line;
string path = #"C:\\Users\\Home\\Desktop\\commands.txt";
WebClient client = new WebClient();
System.IO.Stream stream = client.OpenRead(path);
System.IO.StreamReader str = new StreamReader(stream);
string Text=str.ReadToEnd();
string[] words = Text.Split(':');
if (e.KeyCode == Keys.Enter)
{
for(int i=1;i<words.Length;i++)
{
if (string.compare(words[i],textBox1.text)==0)
{
COMBOX.Items.Add(ConsoleEnter.Text);
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
else
{
COMBOX.Items.Add("Invalid Command");
COMBOX.Items.Remove("");
ConsoleEnter.Text = "";
}
}
}
}
try this ..
use namespace using System.Net;

Categories

Resources