I would like to get the files path of the files selected from the user on the desktop, with this code I can get all file from the explorer
public void GetListOfSelectedFilesAndFolderOfWindowsExplorer()
{
Shell exShell = new Shell();
List<string> selected = new List<string>();
foreach (ShellBrowserWindow window in (IShellWindows)exShell.Windows())
{
// check both for either interface to work
// add an Exit for to just work the first explorer window
if ((window.Document as IShellFolderViewDual) != null)
{
foreach (FolderItem fi in window.Document.SelectedItems)
selected.Add(fi.Path);
}
else if ((window.Document as ShellFolderView) != null)
{
foreach (FolderItem fi in window.Document.SelectedItems)
selected.Add(fi.Path);
}
}
}
I need to get the files names of the files in the desktop, but the list result empty.
the files paths selected is not clear for me, but try the below code to get the list of files and folders in the user desktop
// Get the path of the user's desktop
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// Get the paths of all files and directories on the desktop
string[] files = Directory.GetFiles(desktopPath);
string[] directories = Directory.GetDirectories(desktopPath);
// Create a string to store the paths
string message = "";
// Add all files to the message
foreach (string file in files)
{
message += file + "\n";
}
// Add all directories to the message
foreach (string directory in directories)
{
message += directory + "\n";
}
// Show the message in a message box
MessageBox.Show(message, "Paths of files and directories on desktop", MessageBoxButtons.OK, MessageBoxIcon.Information);
To get list of selected folders or files, first you have to select the folders or files you need, and this must be done using a tool like FolderBrowserDialog and OpenFileDialog.
Here is an example of how you might use the OpenFileDialog to allow the user to select multiple files on the desktop:
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
// Get the paths of the selected files
string[] selectedFiles = openFileDialog1.FileNames;
// Add all files to the list box
foreach (string file in selectedFiles)
{
message += file + "\n";
}
}
And for selecting folders you can use FolderBrowserDialog
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
// Get the path of the selected directory
string directory = folderBrowserDialog1.SelectedPath;
message = directory;
}
Related
I am writing a c# desktop app where I want users to select a file from open file dialog after which the program will copy the file to where the application is executing from: here is my code that is not working at the moment
var dlg = new Microsoft.Win32.OpenFileDialog {
Title = "Select File",
DefaultExt = ".json",
Filter = "Json File (.json)|*.json",
CheckFileExists = true
};
if (dlg.ShowDialog() == true)
{
try
{
var currentDirectory = System.Windows.Forms.Application.ExecutablePath;
var destFile = Path.Combine(currentDirectory + "/temp/", dlg.FileName);
File.Copy(dlg.FileName, destFile, true);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("An error occured: " + ex.Message));
}
}
Now I am getting the error that
the file is being used by another program
. When I edit the code that is meant to initiate the copy by removing true:
File.Copy(dlg.FileName, destFile);
I get the error that the
file already exists
in the directory where it is being selected from.
It seems, that you have an incorrect path to write into.
System.Windows.Forms.Application.ExecutablePath
returns exe file itself, not directory. Try
var destFile = Path.Combine(
Path.GetDirectoryName(Application.ExecutablePath), // Exe directory
"temp", // + Temp subdirectory
Path.GetFileName(dlg.FileName)); // dlg.FileName (without directory)
If you aren't sure that temp exists, you have to create it:
Directory.CreateDirectory(Path.GetDirectoryName(destFile));
Use below Code for Copy file from one folder to another folder.
string[] filePaths = Directory.GetFiles("Your Path");
foreach (var filename in filePaths)
{
string file = filename.ToString();
//Do your job with "file"
string str = "Your Destination"+file.ToString(),Replace("Your Path");
if (!File.Exists(str))
{
File.Copy(file , str);
}
}
Basically I am trying to make a program that empties or even deletes a certain file, the thing is, this file is about 3 or 4 or so folders past the macromedia folder, and it can be it different named folders for anyone, so that is why the string[] files is done like that, it just checks for basically "FlashGame.sol" in EVERY folder after the macromedia folder.
I commented where I need help, I basically need to empty the contents of the file, or just flat out delete it.
private void button1_Click(object sender, EventArgs e)
{
string path = textBox1.Text + "/AppData/Roaming/Macromedia"; //the person using the program has to type in the beginning of the directory, C:/Users/Mike for example
bool Exists = Directory.Exists(path);
try
{
if (Exists)
{
string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
string[] array = files;
for (int i = 0; i < array.Length; i++)
{
string info;
string text = array[i];
using (StreamReader streamReader = new StreamReader(text))
{
info = streamReader.ReadToEnd();
//erase the contents of the file here or even delete it
}
}
}
}
catch
{
MessageBox.Show("The given directory was not found", "Error", MessageBoxButtons.OK);
}
}
You can clear a file this way:
System.IO.File.WriteAllText(#"file.path",string.Empty);
So you should probably change your Code to:
string[] files = Directory.GetFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
foreach (var file in files)
{
System.IO.File.WriteAllText(file, string.Empty);
}
Also take a look at Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), which gives the appdata directory of the current user.
Also never catching a Exception without handling it correctly. You already know, if the directory exists via your Exists Variable.
string path = Environment.ExpandEnvironmentVariables(#"%AppData%\Macromedia\"); // Example C:\Users\Mike\AppData\Roaming\Macromedia\
if (Directory.Exists(path)) {
string[] files = Directory.EnumerateFiles(path, "*FlashGame.sol", SearchOption.AllDirectories);
foreach (string file in files) {
try {
File.Delete(file);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
}
What I have here is the user select a folder full of .txt files from a external drive and a dummy file is made with the filename to a local folder.
I have 2 questions regarding the code below.
How do I verify that the user select a specific folder?
How do I remove the .txt extension? The code copies the file name and creates the files but its labeled "text.txt.png" but I need it to read "text.png".
int g;
private void folderSelect()
{
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.RootFolder = Environment.SpecialFolder.MyComputer;
folder.ShowNewFolderButton = false;
folder.Description = "Select Folder";
if (folder.ShowDialog() == DialogResult.OK)
{
DirectoryInfo files = new DirectoryInfo(folder.SelectedPath);
FileInfo[] textFiles = files.GetFiles("*.txt");
while (g < textFiles.Length)
{
if (g <= textFiles.Length)
{
File.Create("path/" + (textFiles[g].Name + ".png"));
g++;
}
else
{
break;
}
}
}
Note: I tried using Path.GetFileNameWithoutExtension to remove the extension but Im not sure if i was using it correctly.
Any help would be appreciated. Thank you in advance.
const string NEW_PATH = "path/";
if (!Directory.Exists(NEW_PATH))
Directory.CreateDirectory(NEW_PATH);
const string PATH_TO_CHECK = "correctpath";
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.RootFolder = Environment.SpecialFolder.MyComputer;
folder.ShowNewFolderButton = false;
folder.Description = "Select Folder";
if (folder.ShowDialog() == DialogResult.OK)
{
string pathPastDrive = folder.SelectedPath.Substring(Path.GetPathRoot(folder.SelectedPath).Length).ToLower();
// Here it depends on whether you want to check (1) that the path is EXACTLY what you want,
// or (2) whether the selected path just needs to END in the path that you want.
/*1*/ if (!pathPastDrive == PATH_TO_CHECK)
/*2*/ if (!pathPastDrive.EndsWith(PATH_TO_CHECK))
return; // or you can throw an exception if you want
foreach (string textFile in Directory.GetFiles(folder.SelectedPath, "*.txt"))
File.Create(NEW_PATH + Path.GetFileNameWithoutExtension(textFile) + ".png");
}
You can use GetFileNameWithoutExtension, and it makes it pretty easy.
Also, if you're already sure that your new folder exists, then you can elide the first three lines and replace NEW_PATH with "path/" in the last line.
To see the returned path just use the SelectedPath property, then you can compare it to whatever you had in mind. The # before the path just means I don't have to escape any characters, it's the same as "C:\\MyPath".
FolderBrowserDialog folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
if (folder.SelectedPath == #"C:\MyPath")
{
// DO SOMETHING
}
}
You already hit the nail on the head about the file name without extension, change this line:
File.Create("path/" + (textFiles[g].Name + ".png"));
To this:
File.Create("path/" + (Path.GetFileNameWithoutExtension(textFiles[g].Name) + ".png"));
Edit:
To get the folder name you already have the DirectoryInfo object so just use that:
DirectoryInfo files = new DirectoryInfo(folder.SelectedPath);
string folderName = files.Name;
I'm making a button that reads a file path then deletes the files within the folder. It's currently deleting the entire directory. Here's my code:
public void deleteFiles(string Server)
{
string output = "\\\\" + Server + "\\F\\Output";
string input = "\\\\" + Server + "\\F\\Input";
string exceptions = "\\\\" + Server + "\\F\\Exceptions";
new System.IO.DirectoryInfo(input).Delete(true);
new System.IO.DirectoryInfo(output).Delete(true);
new System.IO.DirectoryInfo(exceptions).Delete(true);
}
Would just deleting the directory and recreating it work? Or do you want to preserve permissions?
You are calling Delete method on DirectoryInfo, you should call it on FileInfo's instead:
var files = new DirectoryInfo(input).GetFiles()
.Concat(new DirectoryInfo(output).GetFiles())
.Concat(new DirectoryInfo(exceptions).GetFiles());
foreach(var file in files)
file.Delete();
Another way:
var files = Directory.GetFiles(input)
.Concat(Directory.GetFiles(output))
.Concat(Directory.GetFiles(exceptions));
foreach(var file in files)
File.Delete(file);
DirectoryInfo.Delete and Directory.Delete delete empty directories, if you want to delete files you could try this method:
public void DeleteFiles(string path, bool recursive, string searchPattern = null)
{
var entries = searchPattern == null ? Directory.EnumerateFileSystemEntries(path) : Directory.EnumerateFileSystemEntries(path, searchPattern);
foreach(string entry in entries)
{
try
{
FileAttributes attr = File.GetAttributes(entry);
//detect whether its a directory or file
bool isDir = (attr & FileAttributes.Directory) == FileAttributes.Directory;
if(!isDir)
File.Delete(entry);
else if(recursive)
DeleteFiles(entry, true, searchPattern);
}
catch
{
//ignore
}
}
}
I have a set of files written to a temporary directory which I want to display to the user. In this instance I wish them to be able to select a file and then have the option of saving it. Is there a decent control in C# for doing this?
I think you could use OpenFileDialog and FolderBrowserDialog for example:
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.InitialDirectory = "c:\\";//your temp directory path
dialog.Title = "Select files to move/copy";
if (dialog.ShowDialog() == DialogResult.OK)
{
string[] files = dialog.FileNames;
using (FolderBrowserDialog save = new FolderBrowserDialog())
{
save.Description = "Select location to save files";
if (save.ShowDialog() == DialogResult.OK)
{
foreach (string file in files)
{
FileInfo finfo = new FileInfo(file);
File.Move(file, save.SelectedPath + finfo.Name);
}
}
}
}
}
Would a simple Open File Dialog be sufficent? You can restrict it to only show the files with your temporary extension. OpenFileDialog in C# gives some examples of use.