Can I use the "StreamWriter" function to save the text in the ListBox?
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile1 = new SaveFileDialog();
saveFile1.DefaultExt = "*.txt";
saveFile1.Filter = "Text files|*.txt";
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
{
sw.WriteLine(listBox1.Text);
sw.Close();
}
Property ListBox.Text only works with the selected item. You, I suspect, need all the elements. If the ListBox rows are stored, it is possible to do so:
File.WriteAllLines(saveFile1.FileName, listBox1.Items.OfType<string>());
You should use string SelectedItem of the ListBox
using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
{
sw.WriteLine(listBox1.GetItemText(listBox1.SelectedItem));
sw.Close();
}
If you want to save all items on your Listbox using StreamWriter, loop through all items and pass it on a string, or stringbuilder then write it on your file:
using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
{
string text = "";
foreach (var item in listBox1.Items)
{
text += item.ToString() + Environment.NewLine; //I added new line per list.
}
sw.WriteLine(text);
sw.Close();
}
If you want the selected text instead, you can just use the SelectedItem:
using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
{
sw.WriteLine(listBox1.SelectedItem);
sw.Close();
}
Related
I would like to create the txt file that has name from my textbox1 and at the same time, I would like to write in it text from my textbox2.
Can you help me?
I have tried this
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\felc\Desktop\file\" + textBox1.Text +
".txt";
File.Create(path);
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(textBox1.Text);
}
}
I would suggest you first check if the file already exists, and only create it if not.
Something like:
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\Users\felc\Desktop\file\" + textBox1.Text + ".txt";
if (!File.Exists(path))
{
File.Create(path);
}
using(var tw = new StreamWriter(path, false))
{
tw.WriteLine(textBox2.Text);
}
}
Note : in case you would like your code to append line to the file and not to re-write it, change the secont argument to "true": new StreamWriter(path, true)
Note 2 : You wrote the value of the first text box to the file instead of the second one. hence, in your code the text in the file will be the same as it's name.
using(var tw = new StreamWriter(path, false))
{
tw.WriteLine(textBox2.Text);
}
I would like to open and add a text file content into a list Box, but if I want to add another text file, how do I check if the file that I add is already added into the list Box. I mean I don't want the list box to be duplicated.
private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Text file|*.txt";
openFileDialog.Title = "Open Text";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(openFileDialog.OpenFile()))
{
string line;
while ((line = r.ReadLine()) != null)
{
donutListBox.Items.Add(line);
}
}
}
}
Add an if:
if ( !donutListBox.Items.Contains(line) ){
donutListBox.Items.Add(line);
}
If you on .net framework 4+, you can use File.ReadAllLines(string filename) static method:
private void openAndAddToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Text file|*.txt";
openFileDialog.Title = "Open Text";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var lines = File.ReadAllLines(openFileDialog.FileName);
lines = lines.Where(line => !donutListBox.Items.Contains(line)).ToArray();
donutListBox.Items.AddRange(lines);
}
}
You can try is
public static bool IsFileInUse(string filename)
{
bool locked = false;
try
{
FileStream fs =
File.Open(filename, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
fs.Close();
}
catch (IOException ex)
{
locked = true;
}
return locked;
}
And :
if(!Class.IsFileInUse("FilePAth") && !donutListBox.Items.Contains(line))
{
//your code
}
I'm starting to program in C# and I want to export the data of a ListView to a txt-file, I have this code, but it does not export the data to the txt-file when I press the button destined for this task.
private void export2File(ListView lv, string splitter)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "SaveFileDialog Export2File";
sfd.Filter = "Text File (.txt) | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
filename = sfd.FileName.ToString();
if (filename != "")
{
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (ListViewItem item in lv.Items)
{
sw.WriteLine("{0}{1}{2}", item.SubItems[0].Text, splitter, item.SubItems[1].Text);
}
}
}
}
}
I'm trying to remove out-of-sequence white spaces from a text file to one-space sequence in a winForm i.e.,
From
sagchjvcsj kbschjsdchs sudbjsdbl
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc
To
sagchjvcsj kbschjsdchs sudbjsdbl
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc
My implementation is:
private void buttonBrowse_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialogImage = new OpenFileDialog();
openFileDialogImage.Filter = "Text files | .txt";
openFileDialogImage.Multiselect = false;
if (openFileDialogImage.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialogImage.OpenFile()) != null)
{
textBoxFileName.Text = openFileDialogImage.FileName;
}
}
}
private void buttonGo_Click(object sender, EventArgs e)
{
string path = textBoxFileName.Text;
string s = string.Empty;
using (StreamReader reader = new StreamReader(path, true))
{
s = reader.ReadToEnd();
}
string[] parts = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.ShowDialog();
string pathSave = saveFileDialog.FileName;
File.CreateText(pathSave);
using (StreamWriter sw = new StreamWriter(pathSave))
{
sw.Write(parts);
}
}
}
}
Error that I am getting on line using (StreamWriter sw = new StreamWriter(pathSave)) is:
The process cannot access the file 'E:\test.txt' because it is being used by another process.
I downloaded ProcessWorker to see which process is currently locking Test.txt but I don't see any process using it. Any ideas on how to solve it?
In addition to the other suggestions, your problem is that File.CreateText() will lock so you need to release the lock. I have wrapped the call to File.CreateText() in a using statement to release the lock.
There was an issue with the output of the StreamWriter so I made some changes to get the expected output as per your question.
private void buttonGo_Click(object sender, EventArgs e)
{
string path = textBoxFileName.Text;
string s = string.Empty;
string[] parts;
using (StreamReader reader = new StreamReader(path, true))
{
parts = reader.ReadToEnd().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.ShowDialog();
string pathSave = saveFileDialog.FileName;
using (File.CreateText(pathSave))
{ }
using (StreamWriter sw = new StreamWriter(pathSave))
{
string result = string.Empty;
foreach (string s in parts)
{
result += s + " ";
}
sw.Write(result);
}
}
I have two ListBox controls in my application and a button to save it to a text file. But I want to select using a ComboBox which one to save to save in a text file. The following code illustrates what I am trying to do:
private void button4_Click(object sender, EventArgs e)
{
var ss = listBox1.Items;//first listbox
var sb = listBox2.Items;//second listbox
SaveFileDialog svl = new SaveFileDialog();
svl = saveFileDialog1;
svl.Filter = "txt files (*.txt)|*.txt";
if (svl.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter st = new StreamWriter(S))
foreach (string a in ss) // In here i want set which lisbox I want to save
st.WriteLine(a.ToString());
}
}
What would be a good approach to the problem?
If you add a combobox that holds two items, Listbox1 and Listbox2 the following code will save the items from the listbox selected in the Combobox.
As you can see I add an items local variable that is of type ObjectCollection that is then assigned to using a switch statement.
private void button4_Click(object sender, EventArgs e)
{
ObjectCollection items = null;
switch (combobox1.Text) {
case "ListBox1":
items = listBox1.Items;
break;
case "ListBox2":
items = listBox2.Items;
break;
default:
throw new Exception("no selection");
break;
}
SaveFileDialog svl = new SaveFileDialog();
svl = saveFileDialog1;
svl.Filter = "txt files (*.txt)|*.txt";
if (svl.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter st = new StreamWriter(S))
foreach (string a in items) //the selected objectcollection
st.WriteLine(a.ToString());
}
If you don't have references to your listboxes you could dynamically add the listboxes that are on the form to the combobox in the load event of the form like so:
foreach(var ctl in this.Controls)
{
if (ctl is ListBox)
{
var lb = (ListBox) ctl;
this.comboBox1.Items.Add(lb.Name);
}
}
To find the correct listbox when you click save replace the switch command with this single line:
var items = ((ListBox) this.Controls[combobox1.Text]).Items;
You might want to check if combobox1.Text is emtpy or null but I leave that as an exercise for the reader.