automate openFileDialog process in c# - c#

I have tried this code it would open the file dialog to the correct location and there is only one xml file which needs to selected ( where i need to select it and click on open ) instead of selecting the file and click open to process the file is there any way to disable the open button on open file dialog. Here my xml file changes everyday. i have given *.xml but gives me a error Illegal characters in path.. my file format is this.
lborough vehicles_in 2014-06-05.xml == this changes everyday according to date.
Without clicking on open how to select the file.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "XML Files (*.xml)|*.xml";
string initPath = Path.GetFullPath("C:/Users/IT-Administrator/Desktop/LUVS/");
dialog.InitialDirectory = Path.GetFullPath(initPath);
tblVehicles = new DataTable();
dv = new DataView(tblVehicles);
if (dialog.ShowDialog() == DialogResult.OK)
{
if (dialog.FileName.Length > 0)
{
//Load Schema and Vehicle_In XML file
tblVehicles.ReadXmlSchema(Path.Combine(applicationFolder, "vehicles_in.xsd"));
tblVehicles.ReadXml(dialog.FileName);
this.dataGridView1.DataSource = tblVehicles;
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.ReadOnly = true;
**Update**
I have tried this can you tell me how to open the file from Directory.get files at runtime
string[] filePaths = Directory.GetFiles(#"C:\Users\IT-Administrator\Desktop\LUVS/", "*.xml", SearchOption.AllDirectories);
FileStream stream = File.Open(#"C:\Users\IT-Administrator\Desktop\LUVS*.xml",
FileMode.Open);
tblVehicles = new DataTable();
dv = new DataView(tblVehicles);
tblVehicles.ReadXmlSchema(Path.Combine(applicationFolder, "vehicles_in.xsd"));
tblVehicles.ReadXml(stream);

Your attempted solution at the end doesn't quite get it:
/* Gives you an array of file names */
string[] filePaths = Directory.GetFiles(#"C:\Users\IT-Administrator\Desktop\LUVS/", "*.xml", SearchOption.AllDirectories);
FileStream stream = File.Open(#"C:\Users\IT-Administrator\Desktop\LUVS*.xml",
FileMode.Open);
You aren't using the array, but instead just trying to open a wildcard path; You can't do that. File.Open only accepts a single file path.
Instead, try something more like this:
/* Gives you an array of file names */
string[] filePaths = Directory.GetFiles(#"C:\Users\IT-Administrator\Desktop\LUVS/", "*.xml", SearchOption.AllDirectories);
// Work with each file individually
foreach(var filePath in filePaths)
{
using(FileStream stream = File.Open(filePath, FileMode.Open))
{
tblVehicles = new DataTable();
dv = new DataView(tblVehicles);
tblVehicles.ReadXmlSchema(Path.Combine(applicationFolder, "vehicles_in.xsd"));
tblVehicles.ReadXml(stream);
// Do whatever you need to do with the data from this one file, then move on....
{
}

Is there any reason that you can't use Directory.GetFiles to get all files in a directory and use File.Open to get the file? Why do you want to do this with a FileDialog, if you don't want the FileDialog?
Update:
//Load Schema and Vehicle_In XML file
tblVehicles.ReadXmlSchema(Path.Combine(applicationFolder, "vehicles_in.xsd"));
// Get all XML files from the files directory
string[] filePaths = Directory.GetFiles(#"files\", "*.xml", SearchOption.AllDirectories);
// Read the first XML file in the files directory
tblVehicles.ReadXml(filePaths[0]);
Is this what you asked for?

As you want to select your file and inmediately work with it, you want a button behaviour. Best way here is to make your own UserControl showing files existing on your directory.
1. Get files from directory
2. Show dialog with buttons, every buttons asociated to its file.
3. On button click, close dialog and pass file to your method.

You could use SendKeys() but it's clunky, and if the user moves focus elsewhere you might end up sending the keystrokes to the wrong window.
openFileDialog isn't very customizable, so you might want to consider using openFolderDialog and append the known filename to the user selected directory.

Related

C# winform File.Copy from a SaveDialog

I am attempting to copy a .txt from my application directory or some kind an export feature to users desire path and filename using savedialog on C# my code is below.
private void button2_Click(object sender, EventArgs e)
{
string directory = AppDomain.CurrentDomain.BaseDirectory + "output.txt";
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "txt files (*.txt);
dialog.FilterIndex = 2;
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
}
}
}
But I am getting an error
The given path's format is not supported.
I am new with C# and want to understand this error and in addition, I want to set the file name extention default as .txt also, any suggestion would be great.
There are a couple of things you need to change.
First, of course, is your copy call. This line makes no sense
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
dialog.FileName contains already the full file name of your destination file. So there is no need to extract the directory and then add all the path again. Write just
File.Copy(directory, dialog.FileName);
But this creates a possible error. What if your user doesn't change the destination folder to another directory? You end up writing on the same file you want to read.
So I would add a sanity check like this
if(directory == dialog.FileName)
MessageBox.Show("Copy","Choose a different output folder");
else
File.Copy(directory, dialog.FileName);
Finally, if you want to force the output file to have always the .TXT extension you could add this line to the SaveDialog configuration
// Fix also your filter property. The one you have is invalid
dialog.Filter = "txt files (*.txt)|*.txt";
dialog.FilterIndex = 0; // 2 ?? There is no index 2 in your filter string
dialog.RestoreDirectory = true;
// Force the .TXT extension
dialog.AddExtension = true;

OpenFileDialog reads only the first file

I'm using the following code to open multiple XML files and read the contents of the files but it doesn't work.
OpenFD.Filter = "XML Files (*.xml)|*.xml";
OpenFD.Multiselect = true;
if (OpenFD.ShowDialog() == DialogResult.OK)
{
foreach (string file in OpenFD.FileNames)
{
MessageBox.Show(file);
System.IO.Stream fileStream = OpenFD.OpenFile();
System.IO.StreamReader streamReader = new System.IO.StreamReader(fileStream);
using (streamReader)
{
MessageBox.Show(streamReader.ReadToEnd());
}
fileStream.Close();
}
}
For testing purposes, I created two xml files.
file1.xml (its content is "string1")
file2.xml (its content is "string2")
When I open the dialog and select the two files, I get four messages.
file1.xml
string1
file2.xml
string1
Even though the OpenFileDialog reads the file names correctly, I can't get to read the second file. It only reads the first file. So I'm guessing the problem is related to StreamReader, not to OpenFileDialog. What am I doing wrong?
You're using OpenFD.OpenFile() in each iteration, which:
Opens the file selected by the user, [...] specified by the FileName property.
Which in turn:
can only be the name of one selected file.
Use the file variable from your loop instead, and the StreamReader constructor that accepts a string:
using (var streamReader = new System.IO.StreamReader(file))
{
MessageBox.Show(streamReader.ReadToEnd());
}
This line is opening the file from the OpenFileDialog:
System.IO.Stream fileStream = OpenFD.OpenFile();
But there's no specification for which file. You need a way to distinguish which file you're opening. I would get rid of that line all together and just use the string file you have in the loop.
System.IO.StreamReader streamReader = new System.IO.StreamReader(file);

Make user browse and select a txt file for processing in c#

I want the user to locate a txt file on his computer which will later be used by my code for analysis. Is there a way to do that? One possible way is to make user enter the path of txt file. But that's not how I would prefer it
Thanks
string filename;
var loadDialog = new OpenFileDialog { Filter = "Text File|*.txt", InitialDirectory = #"C:\Your\Start\Directory\" };
if (loadDialog.ShowDialog() == DialogResult.OK)
filename = loadDialog.FileName;

Copy and Rename files in WPF C#

I'm using System.Windows.Forms.OpenFileDialog in my WPF application to select images. When user select an image, I'm displaying file name of selected file in a textbox as below.
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Select image";
fileDialog.InitialDirectory = "";
fileDialog.Filter = "Image Files (*.gif,*.jpg,*.jpeg,*.bmp,*.png)|*.gif;*.jpg;*.jpeg;*.bmp;*.png";
fileDialog.FilterIndex = 1;
fileDialog.RestoreDirectory = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtImagePath.Text = fileDialog.FileName;
}
I have a button as Save in my application. When user click on this button, I need to rename this file to another name and copy it to another directory in my hard drive.
How can I achieve this?
Using File.Copy and methods in the Path class to extract the relevant part of your file
string newDir = #"D:\temp";
string curFile = Path.GetFileName(txtImagePath.Text);
string newPathToFile = Path.Combine(newDir, curFile);
File.Copy(txtImagePath.Text, newPathToFile);
Now the rename operation on the current dir using File.Move
string curDir = Path.GetDirectoryName(textImagePath.Text);
File.Move(txtImagePath.Text, Path.Combine(curDir, "NewNameForFile.txt"));
This code could be improved introducing some error handling
If you want to copy directly the old file in the new dir using the new name then you could write simply
string newPathToFile = #"D:\temp\NewNameForFile.txt";
File.Copy(txtImagePath.Text, newPathToFile);
and then do the rename on the current dir.
How about using:
System.IO.File.Copy
Alternatively, you can start a batch file, using processInfo
You can use File.Copy. Here are the details: http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx. It takes the source file and copies it to a destination, possibly under a new name.

Writing a Text File in memory and saving it with savefiledialog

I am trying to make a text file in memory, add some lines to it and at the end save the file in a text file. I can handle the savedialog part but I dont know how to get the text file from memory. Any help and tips will be appriciated.
What I am doing so far is:
//Initialize in memory text writer
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);
please note
I will call tw.WriteLine() add more lines in different places so I want to save this at end of program (so this shouldent be wrapped between something like using{} )
UPDATE
StringBuilder seems to be a more reliable option for doing this! I get strange cut-outs in my text file when I do it using MemoryStream.
Thanks.
I think your best option here would be to write to a StringBuilder, and when done, File.WriteAllText. If the contents are large, you might consider writing directly to the file in the first place (via File.CreateText(path)), but for small-to-medium files this should be fine.
var sb = new StringBuilder();
sb.AppendLine("HELLO WORLD!");
sb.AppendLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
File.WriteAllText(path, sb.ToString());
Or, something nigh-on the same as #Marc's answer, but different enough that I think it's worth putting out there as a valid solution:
using (var writer = new StringWriter())
{
writer.WriteLine("HELLO WORLD!");
writer.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!");
File.WriteAllLines(path, writer.GetStringBuilder().ToString());
}
Where path is a string representing a valid file system entry path, predefined by you somewhere in the application.
Assume your SaveFileDialog name is "dialog"
File.WriteAllBytes(dialog.FileName, Encoding.UTF8.GetBytes("Your string"));
or
var text = "Your string";
text += "some other text";
File.WriteAllText(dialog.FileName, text);
also in your own solution you can do this :
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);
// just add this
File.WriteAllBytes(dialog.FileName, ms.GetBuffer());
Something like this.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
using (FileStream file = File.CreateText(dlg.FileName)
{
ms.WriteTo(file)
}
}
I haven't worried about whether the file already exists but this should get you close.
You might need a ms.Seek(SeekOrgin.Begin, 0) too.
Another way of appending text to the end of a file could be:
if (saveFileDialog.ShowDialog() == DialogResult.OK) {
using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {
writer.WriteLine(text);
}
}
supposing that text is the string you need to save into your file.
If you want to append new lines to that string in an easy way, you can do:
var sb = new StringBuilder();
sb.AppendLine("Line 1");
sb.AppendLine("Line 2");
and the resulting string will be sb.ToString()
If you already have a Stream object (in your example, a MemoryStream), you can do the same but replace the line:
using (var writer = new StreamWriter(saveFileDialog.Filename, true)) {
by
using (var writer = new StreamWriter(memoryStream)) {
Edit:
About wrapping the statements inside using:
Take in count that this is not a problem at all. In my first example, all you will have to do is to keep that StringBuilder object, and keep adding lines to it. Once you have what you want, just write the data into a text file.
If you are planning to write more than once to the text file, just clear the StringBuilder everytime you write, in order to not get duplicated data.

Categories