I have a checkedListBox; wich loads files inside a folder; to run/open when checked.
What I'm trying to achieve is to:
- Load filenames without extension into the CheckedListBox.
I can retrieve:
"C:\Folder1\anotherfolder\myfile1.txt"
but; i just want to be retrieve: the "filename" (with or without the extention).
Something Like:
"myfile1.txt"
I was attempting to do this with folderBrowserDialog, but I have no idea on how to accomplish this.
My Current Code:
//...
private string openFileName, folderName;
private bool fileOpened = false;
//...
OpenFileDialog ofd = new OpenFileDialog();
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (!fileOpened)
{
ofd.InitialDirectory = fbd.SelectedPath;
ofd.FileName = null;
fbd.Description = "Please select your *.txt folder";
fbd.RootFolder = System.Environment.SpecialFolder.MyComputer;
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string foldername = fbd.SelectedPath;
foreach (string f in Directory.GetFiles(foldername))
checkedListBox1.Items.Add(f);
}
Can anyone point me in the right direction?
Thanks in advance.
You don't need an OpenFileDialog at all, simply change the line that adds the files to
checkedListBox1.Items.Add(Path.GetFileName(f));
Just remember to add
using System.IO;
And you can also reduce everything to one line code
checkedListBox1.Items.AddRange(Directory.GetFiles(fbd.SelectedPath).Select(x => Path.GetFileName(x)).ToArray());
Related
I'm trying to read a list of documents in a directory. I understand how the filter modifiers work at a high level and have used them before. However, this time I need to filter something that doesn't have a standardized extension (i.e. "*.txt" or *.pdf").
I'm using the example as found on....
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.filedialog.filter?view=net-5.0
using System;
using System.Windows.Forms;
namespace COMS2412_Readin
{
public partial class Form1 : Form
{
string Serial_num = null;
string INI_file_dir_temp = null;
string CONFIG_data = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Allow user to enter serial number and load it for useage later.
Serial_num = Serial_number_text.Text;
try
{
using (OpenFileDialog COMS_file_dialog = new OpenFileDialog())
{
COMS_file_dialog.InitialDirectory = "c:\\";
//Have dialog box filter out all files without the .INI extention.
COMS_file_dialog.Filter = "txt files (*.INI)|*.INI|All files (*.*)|*.*"; //Failed
// COMS_file_dialog.Filter = "*.INI"; //Failed
// COMS_file_dialog.Filter = "(*.INI)"; //Failed
// COMS_file_dialog.Filter = "(INI files | *.INI)"; //Failed
COMS_file_dialog.FilterIndex = 2;
COMS_file_dialog.RestoreDirectory = true;
if (COMS_file_dialog.ShowDialog() == DialogResult.OK)
{
//Check to make sure it was the correct file type.
INI_file_dir_temp = COMS_file_dialog.FileName;
}
}
}
catch
{
//Sorry there was an error with opening the file. Please ensure the file is not currently open.
}
}
}
}
The project I'm working on imports config files from an external piece of equipment. The problem is there are literally thousands of files, each with unusual file extensions. For example *.INI is one of the extensions I want to filter. I've tried just entering `*.INI as the argument but it didn't work. What am I missing? Is there a way to alter...
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
to filter specific file extensions?
Finally, have something that works...
openFileDialog.Filter = "(*.INI)|*.INI";
This filters out everything that isn't of the .INI extension. For me specifically, I had to run VS as admin and ensure the files were not hidden.
i am currently trying to redirect a path to save an image in a folder.
The Startup path is:
C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug
I am trying to change it so its like:
C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication
The code i am currently using is:
private void browseBtn_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
//open directory
open.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|ALL Files (*.*)|*.*";
open.FilterIndex = 1;
if(open.ShowDialog() == DialogResult.OK)
{
if(open.CheckFileExists)
{
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
System.IO.File.Copy(open.FileName, paths + "\\Images\\sss.jpg");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any help or ideas on the matter? why isnt it taking off the characters so i can use images as the path
There is nothing wrong with your code:
string source =
#"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
string path = source.Substring(0, source.Length - 10);
Console.WriteLine(path);
//resulting in C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication
....If:
You build the project as "Debug", not "Release"
The image directory and the sss.jpg image do exist.
But the way to get the path the way you do now is just... unsafe (at the very least). Try to use Path.Combine and string.Split("\\") instead:
string source = #"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
string[] items = source.Split('\\');
string path = Path.Combine(string.Join("\\", items.Take(items.Length - 2)), "Images\\sss.jpg");
It seems, that you actually want to cut 2 subdirectories off and then combine with \Images\sss.jpg:
String source =
#"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
String[] items = source.Split(new Char[] {
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
String path = String.Join(
Path.DirectorySeparatorChar.ToString(), items.Take(items.Length - 2));
String result = Path.Combine(path, #"Images\sss.jpg");
There's nothing wrong with your code and should work just fine so long as the Images directory exists. Just use
if (!Directory.Exists(Path.Combine(path, "Images")))
Directory.Create(Path.Combine(path, "Images")))
Is there any reason not to just leverage DirectoryInfo? It looks like you just want to go up two directories. You should be able to use DirectoryInfo.Parent to get the path you need without needing to do string manipulation.
DirectoryInfo startupDirectory = new DirectoryInfo(Application.StartupPath);
DirectoryInfo twoDirectoriesUp = startupDirectory.Parent.Parent;
string fullDirectoryName = twoDirectoriesUp.FullName;
I have recently started to get an error which states my directory can not be found I have tried a number of ways to solve this but have yet to find a solution.
The method should allow the user to select an image for their computer and add it to a folder called images inside the applications folder structure. The problem is that when using the File.copy(imageFilename, path); it throws the error. I have tried changing the path and you will see from the code snip it. It is even doing it when the program itself has passed the file path for the application and is still throwing me the error.
this is the method.
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory;
System.IO.File.Copy(imageFile.FileName, path);
}
}
}
I am using VS2013 and have included the using Microsoft.win32
Any further information needed please ask.
Thanks
There are 2 things need to be taken into consideration
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
string path = AppDomain.CurrentDomain.BaseDirectory; // You wont need it
System.IO.File.Copy(imageFile.FileName, path); // Copy Needs Source File Name and Destination File Name
}
}
}
string path = AppDomain.CurrentDomain.BaseDirectory; You won need this because the default directory is your current directory where your program is running.
Secondly
System.IO.File.Copy(imageFile.FileName, path); Copy Needs Source File Name and Destination File Name so you just need to give the file name instead of path
so your updated code will be
private void btnImageUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog imageFile = new OpenFileDialog();
imageFile.InitialDirectory = #"C:\";
imageFile.Filter = "Image Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
imageFile.FilterIndex = 1;
if (imageFile.ShowDialog() == true)
{
if(imageFile.CheckFileExists)
{
System.IO.File.Copy(imageFile.FileName, SomeName + ".jpg"); // SomeName Must change everytime like ID or something
}
}
}
I'm not sure if that's the problem, but the File.Copy method expects a source file name and a target file name, not a source file name and directory: https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx
So, to make this work, in your case you'd have to do something like the following (namespaces omitted):
File.Copy(imageFile.FileName, Path.Combine(path, Path.GetFileName(imageFile.FileName));
Note that this will fail if the destination file exists, to overwrite it, you need to add an extra parameter to the Copy method (true).
EDIT:
Just a note, the OpenFileDialog.CheckFileExists does not return a value indicating if the selected file exists. Instead, it is a value indicating whether a file dialog displays a warning if the user specifies a file name that does not exist. So instead of checking this property after the dialog is closed, you should set it to true before you open it (https://msdn.microsoft.com/en-us/library/microsoft.win32.filedialog.checkfileexists(v=vs.110).aspx)
I have created an OpenFileDialog object, called openFileDialog.
When calling openFileDialog.ShowDialog I want to be able to select files having only the extension ".abc" and not ".abcd".
Using the property:
this.openFileDialog.Filter = "*.abc";
does not work. ".abcd" files can also be selected.
Here is the full code:
var openFileDialog = GetOpenFileDialog("abc",
"*.abc",
"anything (*.abc)|*.abc",
"Select abc file to import...");
if (openFileDialog.ShowDialog() == DialogResult.OK)
{ DoJob(); }
Where GetOpenFileDialog is:
private OpenFileDialog GetOpenFileDialog(string defaultExt, string fileName, string filter, string title)
{
return new OpenFileDialog
{
DefaultExt = defaultExt,
FileName = fileName,
Filter = filter,
Title = title,
};
}
I would appreciate any help. Thanks!
Use the filter option of the OpenFileDialog
this.openFileDialog.Filter = "abc files (*.abc)|*.abc"
There is simply a filter property for FileDialogs - http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filter.aspx
I have a requirement in WPF/C# to click on a button, gather some data and then put it in a text file that the user can download to their machine. I can get the first half of this, but how do you prompt a user with a "Save As" dialog box? The file itself will be a simple text file.
Both answers thus far link to the Silverlight SaveFileDialogclass; the WPF variant is quite a bit different and differing namespace.
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
string filename = dlg.FileName;
}
SaveFileDialog is in the Microsoft.Win32 namespace - might save you the 10 minutes it took me to figure this out.
Here is some sample code:
string fileText = "Your output text";
SaveFileDialog dialog = new SaveFileDialog()
{
Filter = "Text Files(*.txt)|*.txt|All(*.*)|*"
};
if (dialog.ShowDialog() == true)
{
File.WriteAllText(dialog.FileName, fileText);
}
Use the SaveFileDialog class.
You just need to create a SaveFileDialog, and call its ShowDialog method.
All the examples so far use the Win32 namespace, but there is an alternative:
FileInfo file = new FileInfo("image.jpg");
var dialog = new System.Windows.Forms.SaveFileDialog();
dialog.FileName = file.Name;
dialog.DefaultExt = file.Extension;
dialog.Filter = string.Format("{0} images ({1})|*{1}|All files (*.*)|*.*",
file.Extension.Substring(1).Capitalize(),
file.Extension);
dialog.InitialDirectory = file.DirectoryName;
System.Windows.Forms.DialogResult result = dialog.ShowDialog(this.GetIWin32Window());
if (result == System.Windows.Forms.DialogResult.OK)
{
}
I'm using an extension method to get the IWin32Window from the visual control:
#region Get Win32 Handle from control
public static System.Windows.Forms.IWin32Window GetIWin32Window(this System.Windows.Media.Visual visual)
{
var source = System.Windows.PresentationSource.FromVisual(visual) as System.Windows.Interop.HwndSource;
System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
return win;
}
private class OldWindow : System.Windows.Forms.IWin32Window
{
private readonly System.IntPtr _handle;
public OldWindow(System.IntPtr handle)
{
_handle = handle;
}
System.IntPtr System.Windows.Forms.IWin32Window.Handle
{
get { return _handle; }
}
}
#endregion
Capitalize() is also an extension method, but not worth mentioning as there are plenty of examples of capitalizing the first letter of a string out there.