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
}
Related
I've created a program where users can input a few information and then can save everything into an xml file, or open it.
Before I setup that save and open thing on the bigger scale, I created a small test-run to find a solution. There are three textboxes where you can input your own information, two checkboxes and comboboxes where users can choose from a few options. I've created a open and save menu-strip-button but can't think of a way how to save all those information into a xml.file.
using System;
using System.IO;
using System.Windows.Forms;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void openToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "XML-File | *.xml|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
//Read the contents of the file into a stream
var fileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
}
}
//MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "XML-File | *.xml|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
/*private void validateUserEntry()
{
// Checks the value of the text.
if (textBox1.Text.Length == 0 && textBox2.Text.Length == 0 && textBox3.Text.Length == 0)
{
// Initializes the variables to pass to the MessageBox.Show method.
string message = " AAAAAAAAAAAAA";
string caption = "Error Detected in Input";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
DialogResult result;
// Displays the MessageBox.
result = MessageBox.Show(message, caption, buttons);
if (result == System.Windows.Forms.DialogResult.Yes)
{
// Closes the parent form.
this.Close();
}
}
}*/
}
}
I use the library I wrote by using the System.Xml.Serialization library in XML operations.
You can download the source codes or use them with the nuget package manager.
ioCode.Serialization
C# types serialization library.
Serializes and deserializes objects into and from XML documents.
PM> Install-Package ioCode.Serialization -Version 1.0.0
Classes
ioCode.Serialization library has two serialization classes
XmlSerializer<T> Xml serialization object to serialize custom types
BinSerializer<T> Bin serialization object for XML-based serialization of custom types. The serialized output file is encrypted.
XmlSerializer<T>
Write to file
Product product = new Product();
product.Name = "Product1";
bool isSuccess = XmlSerializer<Product>.WriteFile(#"C:\users\[user]\documents\product.xml", product);
MessageBox.Show(isSuccess ? "Success" : "Fail");
Read from file
Product product = XmlSerializer<Product>.ReadFile(#"C:\users\[user]\documents\product.xml");
MessageBox.Show((product != null) ? "Success" : "Fail");
BinSerializer<T>
Write to file
Product product = new Product();
product.Name = "Product1";
bool isSuccess = BinSerializer<Product>.WriteFile(#"C:\users\[user]\documents\product.bin", "password123", product);
MessageBox.Show(isSuccess ? "Success" : "Fail");
Read from file
Product product = BinSerializer<Product>.ReadFile(#"C:\users\[user]\documents\product.bin", "password123");
MessageBox.Show((product != null) ? "Success" : "Fail");
I am using C# and a winform and am saving data to a .xlsx on a button click event. I have a unique situation that I am not sure how to code for....
If the form is still displayed and the user clicks the button, I want it to prompt for a file name and save location. BUT if the form has not been closed and the user clicks the button a second time, I want .xlsx to be saved in the same location and with the same filename and over write with no prompt.
This is the syntax I use to prompt for save name and location, but how do I check to determine if a filename/save location has already been input and if it has do not prompt again?
private void btnOne_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { Messagebox.Show("An error has occured"; }
}
}
So, whether the data has a set filename is a part of the state of the class. Inside the class where you have btnOne_Click, just define a string with the filename, defaulted to null:
string filepath = null;
Then, in your btnOne_Click, you want to check for the filepath. If it's not there, open the saveAs dialog. After that, if filepath is set, just save. It will be restructured like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (filepath == null)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK) {
filepath = save.FileName;
}
}
if (filepath != null)
{
try
{
var file = new FileInfo(filepath);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"; }
}
}
This logical structure gives you standard behavior for when a user presses a save button. If they cancel the saveAs dialog, then the save is aborted and the filename state is not changed.
Declare this globally:
public string Filename;
Then change your subroutine like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(Filename))
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
Filename = save.FileName;
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"); }
}
}
else
{
var file = new FileInfo(Filename);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
}
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 application with Listbox and files, each time i press on Add button the default C drive open and i want the application to remember the last path i used
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = "c:\\";
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
Save the last directory used in a global variable like this:
private string _lastPath = string.Empty;
then after the file selection initialize it:
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
when you reopen the dialog set the InitialDirectory with this check:
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
and remove the thisDialog.FileName = lastPath;
EDIT --- UPDATE OF YOUR CODE ---
// This at the global level of your form
private string _lastPath = string.Empty;**
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
You can use a Visual Studio have the last path value for every execution of the application.
Only have to go to Project Properties->Configuration and add a value descriptor.
Example:
Name = LastPath; Type = string; Scope = User; Value = "Default path";
And then after you rebuild yout application, you can set this property this way:
Settings.Default.LastPath = LastPathSelected;
later, you can retrieve the value with:
thisDialog.InitialDirectory = Settings.Default.LastPath;
thisDialog.InitialDirectory = Path.GetDirectoryName(lastPath);
Yes, you can use the OpenFileDialog.InitialDirectory property. Note: you are setting the directory and not the file. So be sure to remove the filename from the path.
more info here
remove this line and you have the last path
thisDialog.InitialDirectory = "c:\\";
If I set path = "C:\\MSREAD.txt"; and Click on SaveAs Menu Item ,it saves Filetext,But If I dont give the String path and save it from saveFD.FileName it doesnt work.Please help me with this issue.
Thanks a lot
public void SaveToFile()
{
String SavedFile = "";
saveFD.InitialDirectory = #"C:";
saveFD.Title = "Save a Text File";
saveFD.FileName = "";
RichTextBox richTextBox1 = new RichTextBox();
saveFD.Filter = "Text Files|*.txt|All Files|*.*";
try
{
if (saveFD.ShowDialog() != DialogResult.Cancel)
{
SavedFile = saveFD.FileName;
path = SavedFile.ToString();
//path = "C:\\MSREAD.txt";
MessageBox.Show(path);
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveToFile();
}
public void SaveMyTextBoxContents(string path)
{
if (listBoxItems.SelectedIndex == -1)
{
if (rdBtnSlow.Checked && rdBtnNo.Checked)
{
using (StreamWriter outputFile = new StreamWriter(path))
{
foreach (string item in listBoxItems.Items)
{
saveAllText = slowNo + " " + item;
outputFile.WriteLine(saveAllText);
}
}
}
}
}
Here is your problem:
richTextBox1.SaveFile(path, RichTextBoxStreamType.PlainText);
SaveMyTextBoxContents(path);
You first save the richTextBox text to file, but then override the same file with SaveMyTextBoxContents, However the file is empty because of SaveMyTextBoxContents method will only save something if some conditions are true "not selected item and both check boxes are checked", and the listBoxItems.Items.Count > 0 which apparently not the case