I'm usin Windows.Forms aplication and I can get files or directory from my user using OpenFileDialog or FolderBrowserDialog. But I need get both in a unique dialog. I Try use OpenFileDialog with .multselect = true and select files and folders, but in code when I acess OpenFileDialog.FileNames this property returns only a file names, never a selected directory.
Exists a static method in System.IO.Directory call GetFileSystemEntries that do exactly I want. But I need a Dialog that do it.
Anyone can help me?
It is not possible to get folder and files with inly a single
dialog().
According to microsoft's documentation about c# You have to use different dialog to select folder and files
try :
string baseFolder = System.IO.Directory.GetParent(strToFile).ToString();
This will give you the folder name of the file.
or use FileInfo!
FileInfo fi = new FileInfo(strToFile);
string fileFolder = fi.DirectoryName;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
if (files != null && files.Length > 0)
{
// returns the root directory
string folder = System.IO.Path.GetDirectoryName(files[0]);
// Obtain the file system entries in the directory path.
string[] directoryEntries =
System.IO.Directory.GetFileSystemEntries(folder);
}
}
}
Related
The product I'm using is a Beijer HMI, currently i can generate a report and save it to a known location (my desktop - C:\Users\mrdav\Desktop).
I need to be able to search on my desktop for a file extension .xls and change its name.
When the report is generated by the HMI, it uses the date and time which means when the file is generated the name will be different every time.
On the press of a button i need to search my desktop for the .xls file and change its name to a variable.
// This is my variable with my program
string NewName = Globals.Tags.Tag1.Value;
The code that is generated needs to sit within the below example.
public partial class Screen1
{
void Button1_Click(System.Object sender, System.EventArgs e)
{
// Code to be added here...
}
}
Hopefully someone can help, I’m using windows compact framework so limited on functionality.
Any questions please let me know.
Thanks in advance,
Dave
Here is an example how you can do that:
DirectoryInfo dir = new DirectoryInfo(sExportPath);
FileInfo[] Files = dir.GetFiles("*.csv");
foreach(FileInfo file in Files )
{
// rename file
System.IO.File.Move(file.FullName, GenerateNewFileName());
}
//elsewhere in the class
private string GenerateNewFileName()
{
//here is where you implement creating or getting the filename that you want your file to be renamed to. An example might look like the below
string serialNumber = GetSerialNumber(); //Get the serial number that you talked about in the question. I've made it a string, but it could be an int (it should be a string)
return Path.ChangeExtension(serialNumber,".xls"); //to use path you will need a using statement at the top of your class file 'using System.IO'
}
This seems to work...but i know its not as tidy as it could be.
Any suggestions?
Thanks to all that helped, got there in the end!
void Button_Click(System.Object sender, System.EventArgs e)
{
try
{
// Location for new file
string NewFileName = #"c:\users\mrdav\desktop\testfolder\";
// Add varibale name to new file
NewFileName += Globals.Tags.Tag1.Value;
// add .xls extention to new file
NewFileName += ".xls";
//show new file name to check all ok
MessageBox.Show (NewFileName);
//search for .xls in known directory
DirectoryInfo di = new DirectoryInfo(#"c:\users\mrdav\desktop");
FileInfo[] Files = di.GetFiles("*.xls");
// if files exist with .xls extention
foreach(FileInfo file in Files )
{
// show full file name
MessageBox.Show (file.FullName);
//rename old file to new file name and move to new folder
File.Move(file.FullName, NewFileName);
}
}
catch (Exception ex)
{
MessageBox.Show (ex.ToString());
}
}
I have an issue with an C# application. I am trying to read some PDF files and load the data into a database.
The application make works good only when the PDF files are in a specific folder. the folder is the debug folder of the project.
I need to load the PDF files from any folder.
public string LecturaPDF(string nombreArchivo)
{
PdfReader lectorPDF = new PdfReader(nombreArchivo);
string TextoPuro = string.Empty;
string[] TextoDividido;
string TextoFinal = string.Empty;
for (int a = 1; a <= lectorPDF.NumberOfPages; a++)
{
ITextExtractionStrategy pdfParser =
new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
TextoPuro = TextoPuro + PdfTextExtractor.GetTextFromPage(lectorPDF, a, pdfParser);
}
lectorPDF.Close();
TextoDividido = TextoPuro.Split('\n');
for (int b = 0; b < TextoDividido.Count(); b++)
{
if (TextoDividido[b].First()== '7')
{
TextoFinal = TextoFinal + TextoDividido[b] + ";";
}
}
return ';' + TextoFinal;
}
the error occur in this line PdfReader lectorPDF = new PdfReader(nombreArchivo);
the error say:
C:\user\me\MyDocuments\Projects\Project1\bin\debug\test.pdf not found
as file or resource
With this function I open a dialog box to select the file and call the function to read the pdf file:
private void cmdProcesar_Click(object sender, RoutedEventArgs e)
{
if (dialogoArchivo.ShowDialog().Value)
{
for (int a = 0; a < dialogoArchivo.FileNames.Count(); a++)
{
lblEstado.Dispatcher.Invoke(DispatcherPriority.Background, (Action)(() => lblEstado.Content =
"Procesando archivos contra Billing..."));
archivo.InsercionArchivo(dialogoArchivo.SafeFileNames[a], G_Fecha,
archivo.LecturaPDF(System.IO.Path.GetFullPath(dialogoArchivo.SafeFileNames[a])),
Convert.ToDouble(txtTarifa.Text),
conexion.ConexionOracle);
}
}
This is my first time with C# and I don't know why only works wwhen I read the files from the project debug folder
Any advice will appreciated
Thanks in advance
UPDATE
private void cmdProcesar_Automatico(object sender, RoutedEventArgs e)
{
string carpeta = "C:\\temp";
DirectoryInfo dir = new DirectoryInfo(carpeta);
FileInfo[] documentos = dir.GetFiles("*.pdf");
txtTarifa.Text = "1.48";
foreach (FileInfo archivopdf in documentos)
{
lblEstado.Dispatcher.Invoke(DispatcherPriority.Background, (Action)(() => lblEstado.Content =
"Procesando archivos contra Billing..."));
archivo.InsercionArchivo(archivopdf.Name, G_Fecha,
archivo.LecturaPDF(System.IO.Path.GetFullPath(archivopdf.Name)),
Convert.ToDouble(txtTarifa.Text),
conexion.ConexionOracle);
}
}
I change the function to automatically read all the file in a specific folder and process every file.
But I get the same error:
C:\user\me\MyDocuments\Projects\Project1\bin\debug\test.pdf not found
as file or resource
From the documentation of OpenFileDialog.SafeFileNames (emphasis mine):
Gets an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path.
As it doesn't contain the path, the current path will be used which when you're running in the debugger will be bin\debug by default.
If you know the directory that the file should be chosen from you could add it to the file name (using Path.Combine) but if you would prefer the full path you can use the FileNames property which according to the documentation (again, emphasis mine):
Each file name includes both the file path and the extension. If no files are selected, this method returns an empty array.
In your context you'd need to change this line:
archivo.LecturaPDF(System.IO.Path.GetFullPath(dialogoArchivo.SafeFileNames[a])),
to
archivo.LecturaPDF(System.IO.Path.GetFullPath(dialogoArchivo.FileNames[a])),
EDIT
To answer the question in your edit - you are getting FileInfo objects for all pdf files in C:\temp but you are then using System.IO.Path.GetFullPath(archivopdf.Name) to get the file path to pass to archivo.LecturaPDF. The documentation for Path.GetFullPath states (emphasis mine again):
This method uses current directory and current volume information to fully qualify path. If you specify a file name only in path, GetFullPath returns the fully qualified path of the current directory.
Imagine that you have a FileInfo for the file c:\temp\example.pdf. When you call System.IO.Path.GetFullPath(archivopdf.Name) on that FileInfo you are essentially calling System.IO.Path.GetFullPath("example.pdf"). This will give the file name of example.pdf but it will use the current path for the path which in your case is C:\user\me\MyDocuments\Projects\Project1\bin\debug\ (the path your executable is running from).
This results in a fully qualified file name of C:\user\me\MyDocuments\Projects\Project1\bin\debug\example.pdf which isn't what you want and presumably doesn't exist.
As you already have a FileInfo object the solution is straightforward - you can use the FullName property directly without the need to call GetFullPath. The FullName property will give you the correct fully qualified name of c:\temp\example.pdf.
Your code should therefore read:
archivo.InsercionArchivo(archivopdf.Name, G_Fecha,
archivo.LecturaPDF(archivopdf.FullName),
Convert.ToDouble(txtTarifa.Text),
conexion.ConexionOracle);
I want to create a browse (OpenFile Dialog) Button to search my local drive and then write out the selected file name (not the full path ) to a TextBox. It should show Only .dat extension files.
I am using Visual Studio 2008
Any help much appreciated!
Next time you ask anything, show some examples of what you have tried please.
private string GetDatFileName()
{
// Create Open File Dialog with the correct filter
using (OpenFileDialog ofd = new OpenFileDialog()) {
ofd.Filter = "dat-file (*.dat) | *.dat";
string fileNameAndFolder = "";
string fileName = "";
// Get file plus folder.
if (ofd.ShowDialog() == DialogResult.OK)
{
fileNameAndFolder = ofd.FileName;
// Split folder and filename
fileName = Path.GetFileName(fileNameAndFolder);
}
// Return the fileName;
return fileName;
}
}
What I have done here is create an OpenFileDialog and set its filter to the required "dat"-format. Only .dat-files will show up in the browserdialog.
Next, you show the dialog and check if the result is OK. If the result is, you will get the full filename (with folder) into a variable. All thats left then, is to get the filename from fileNameAndFolder.
I am working on a WinForm Application using c#. I am using a button to browse for an image file (.jpeg or .bmp). When the user browses the file and clicks ok, on the click of another "Proceed or Update" button, I want that the browsed file should be renamed and saved to a predefined directory where all image files will be saved by default, without much user interaction!
How can I achieve this? I have used openFileDialog for browsing the file, but dont know what else to do.
//detination filename
string newFileName = #"C:\NewImages\NewFileName.jpg";
// if the user presses OK instead of Cancel
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//get the selected filename
string filename = openFileDialog1.FileName;
//copy the file to the new filename location and overwrite if it already exists
//(set last parameter to false if you don't want to overwrite)
System.IO.File.Copy(filename, newFileName, true);
}
More information on the Copy method.
First you have to implement a copy function that can make unique file names:
private void CopyWithUniqueName(string source,
string targetPath,
string targetFileName)
{
string fileName = Path.GetFileNameWithoutExtension(targetFileName);
string extension = Path.GetExtension(targetFileName);
string target = File.Exists(Path.Combine(targetPath, targetFileName);
for (int i=1; File.Exists(target); ++i)
{
target = Path.Combine(targetPath, String.Format("{0} ({1}){2}",
targetFileName, i, extension));
}
File.Copy(source, target);
}
Then you can use it, suppose defaultTargetPath is the default target file where to copy images and defaultFileName is the default file name for images:
void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() != DialogResult.OK)
return;
CopyWithUniqueName(openFileDialog1.FileName,
defaultTargetPath, defaultFileName);
}
In case of multiple selection:
foreach (string fileName in openFileDialog1.FileNames)
{
CopyWithUniqueName(fileName,
defaultTargetPath, defaultFileName);
}
You'll get this (suppose defaultFileName is "Image.png"):
Source Target
A.png Image.png
B.png Image (1).png
C.png Image (2).png
You can do that with the File.Copy()-method. Just put the predefined directory and the new filename as the destination parameter.
For more info see here
I'm trying to build a copier so that you use the openFileDialog to chose a file and then the folderBrowserDialog to choose the location to copy it to.
The problem I'm having is that when I use File.Copy(copyFrom,copyTo) it gives me an exception that I can't copy to a directory.
Is there anyway around this, or am I just missing something stupid and noobish. I've tryed useing openFD for choosing both locations and have just tried using the folderBD to see if it made a difference.
I know there should be if statements there to catch the exceptions but this is a rough draft of the code to get working 1st.
Thanks in advance for the help, code attached.
// Declare for use in all methods
public string copyFrom;
public string copyTo;
public string rootFolder = #"C:\Documents and Settings\cmolloy\My Documents";
private void btnCopyFrom_Click(object sender, EventArgs e)
{
// uses a openFileDialog, openFD, to chose the file to copy
copyFrom = "";
openFD.InitialDirectory = rootFolder;
openFD.FileName = "";
openFD.ShowDialog();
// sets copyFrom = to the file chosen from the openFD
copyFrom = openFD.FileName;
// shows it in a textbox
txtCopyFrom.Text = copyFrom;
}
private void btnCopyTo_Click(object sender, EventArgs e)
{
//uses folderBrowserDialog, folderBD, to chose the folder to copy to
copyTo = "";
this.folderBD.RootFolder = System.Environment.SpecialFolder.MyDocuments;
this.folderBD.ShowNewFolderButton = false;
folderBD.ShowDialog();
DialogResult result = this.folderBD.ShowDialog();
// sets copyTo = to the folder chosen from folderBD
copyTo = this.folderBD.SelectedPath;
//shows it in a textbox.
txtCopyTo.Text = copyTo;
}
private void btnCopy_Click(object sender, EventArgs e)
{
// copys file
File.Copy(copyFrom, copyTo);
MessageBox.Show("File Copied");
You have to append the file name to the directory path. Do this:
string destinationPath = Path.Combine(copyTo, Path.GetFileName(copyFrom));
File.Copy(copyFrom, destinationPath);
(with this you'll copy selected file to another directory with the same name of the original one and it'll throw an exception if the same file already exist in that directory)
Edit
Side note: do not hard code the path in your source code, use this:
rootFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
to get the path of current user's documents folder.
Do this:
File.Copy(copyFrom, Path.Combine(copyTo, Path.GetFileName(copyFrom)));
File.Copy needs to know the full path of the new file you want, including the file name. If you just want to use the same file name, you can use this to append the file name to the path:
copyTo = Path.Combine(copyTo, Path.GetFileName(copyFrom));