how to move files to multiple folders? - c#

i have multiple folders. they are named by file extension names. (ex:- doc, dwg, jpg....etc) my list box data source have more files.(ex:- abc.dwg, beauty.jpg, arc.doc.....) i want to move doc files to doc folder, jpg files to jpg folder, dwg files to dwg folder...etc
how to do it single button click >>"create folders" button use
List<string> fileNames = null;
List<string> fileExtensions = null;
private void btn_list_Click(object sender, EventArgs e)
{
listBox_ex.Items.Clear();
using (FolderBrowserDialog FBD = new FolderBrowserDialog())
{
if (FBD.ShowDialog() == DialogResult.OK)
{
lbl_path.Text = FBD.SelectedPath;
fileNames = Directory.GetFiles(FBD.SelectedPath).ToList();
fileExtensions = fileNames.Select(item => Path.GetExtension(item)
.Replace(".", "")).Distinct().OrderBy(n => n).ToList();
listBox_name.DataSource = fileNames.Select(f => Path.GetFileName(f)).ToList();
listBox_ex.DataSource = fileExtensions;
}
}
}
private void btn_CreateFolder_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog FBD = new FolderBrowserDialog())
{
if (FBD.ShowDialog() == DialogResult.OK)
{
lbl_pathCreated.Text = FBD.SelectedPath;
fileExtensions.ForEach(item =>
Directory.CreateDirectory(Path.Combine(FBD.SelectedPath, item)));
}
}
}

The short answer is that you would simply call File.Move, and pass the full path to the existing file as the first argument, and the full path and file name for the destination.
You can build the destination path and then move the files like:
foreach (string file in fileNames)
{
// Build the destination path
var destination = Path.Combine(
FBD.SelectedPath, // The root destination folder
Path.GetExtension(file).Replace(".", ""), // The file extension folder
Path.GetFileName(file)); // The file name (including extension)
// Move the file
File.Move(file, destination);
}

Related

Skip file renaming conversation if #2 or #3 or #(any number) exist in the file name

Below is my code where I am successfully renaming only the files inside a a folder and also crawls inside every subfolders and renames the entire .png files.
I am trying to add a customization where if the file name already got #1 or #5 or any #(number) then i want the conversation to skip that file and go to next file
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenameAllPngFiles(folderDlg.SelectedPath);
}
private void RenameAllPngFiles(string directoryPath)
{
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath))
{
RenameCurrentPng(item.FullName);
}
}
private void RenameCurrentPng(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png"))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
private DirectoryInfo[] GetDirectoryInfos(string directoryPath)
{
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
Just use the String.Contains method to check for #.
private void RenameCurrentPng(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png"))
{
string ShortFileName = System.IO.Path.GetFileNameWithoutExtension(originalFullFileName);
if (!ShortFileName.Contains("#"))
{
// The new file name without path
var newFileName = $"{ShortFileName}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}

How do I get and display all the file sizes from the file array

I am new to programming, currently trying to get all the file sizes from the file array and display next to them. I found the solution which is FileInfo, but have no idea how it works and couldn't find any solution online. The file array retrieved and display successfully before I added the FileInfo line.
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
string[] files = Directory.GetFiles(FBD.SelectedPath);
string[] dirs = Directory.GetDirectories(FBD.SelectedPath);
foreach (string file in files)
{
long length = new FileInfo(FBD.SelectedPath).Length; //FileNotFoundException
listBox1.Items.Add(Path.GetFileName(file + length));
}
foreach (string dir in dirs)
{
listBox1.Items.Add(Path.GetFileName(dir));
}
}
}
I have a button which can open the folder dialog and user are able to select the directory, and a listbox to display all the file/directory from the selected path. Can I actually get all the files sizes along the path and display next to the files/ directory?
Not with Directory.GetFiles you can't - it returns an array of strings that are filepaths. You'd have to make a new FileInfo from each one and get its length.. It'd be better to call the method of DirectoryInfo that returns you an array of FileInfo to start with:
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
FileInfo[] files = new DirectoryInfo(FBD.SelectedPath).GetFiles();
string[] dirs = Directory.GetDirectories(FBD.SelectedPath);
foreach (FileInfo file in files)
{
listBox1.Items.Add(file.Name + "(" + file.Length + " bytes)");
}
foreach (string dir in dirs)
{
listBox1.Items.Add(Path.GetFileName(dir));
}
}
}
I'm not really sure what you mean by "Can I actually get all the files sizes along the path and display next to the .. directory"
Directories don't have a file size; did you mean that you want the sum total of all the files' sizes inside the directory? For all subdirectories in the hierarchy or the top directory only? Perhaps something like this:
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
FileInfo[] files = new DirectoryInfo(FBD.SelectedPath).GetFiles();
DirectoryInfo[] dirs = new DirectoryInfo(FBD.SelectedPath).GetDirectories();
foreach (FileInfo file in files)
{
listBox1.Items.Add(file.Name + "(" + file.Length + " bytes)");
}
foreach (DirectoryInfo dir in dirs)
{
listBox1.Items.Add(dir.Name + "(" + dir.GetFiles().Sum(f => f.Length) + " bytes)");
}
}
}
For Sum to work you'll have to have imported System.Linq
Incidentally, I present the following as a commentary on why your code didn't work:
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog()==DialogResult.OK)
{
listBox1.Items.Clear();
string[] files = Directory.GetFiles(FBD.SelectedPath);
string[] dirs = Directory.GetDirectories(FBD.SelectedPath);
foreach (string file in files) //ok, so file is the filepath
{
//it doesn't work because you put "FBD.SelectedPath" in instead of "file"
// FBD.SelectedPath is a directory, not a file, hence the FileNotFoundException
//But the real problem is probably a cut n paste error here
long length = new FileInfo(FBD.SelectedPath).Length;
//it would work out but it's a weird way to do it, adding the length on before you strip the filename out
//Path doesnt do anything complex, it just drops all the text before the
//last occurrence of /, but doing Path.GetFilename(file) + length would be better
listBox1.Items.Add(Path.GetFileName(file + length));
}
foreach (string dir in dirs)
{
//need to be careful here: "C:\temp\" is a path of a directory but calling GetFilename on it would return "", not temp
listBox1.Items.Add(Path.GetFileName(dir));
}
}
}
You almost had it right, try the following:
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
if (folderBrowser.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
string[] files = Directory.GetFiles(folderBrowser.SelectedPath);
foreach (string file in files)
{
var fileInfo = new FileInfo(file);
listBox1.Items.Add($"{Path.GetFileName(file)} {fileInfo.Length} bytes.");
}
}
}

How to use Zipfile to extract all files in one directory

ith my simple C# form app I want to click a button(FolderBrowserDialog) and navigate to a folder on my computer.
This folder will contain dozens of zip files. I will then select this folder.
In the folder that I had selected, the program should then create one subfolder for each zip file, name the subfolders with the name of their respective zip files, and decompress the content of the zip files in their respective subfolders.
In my code (below) I have no problems in selecting the parent folder and assigning the path to a string variable sbDir.
The problem I am having is passing sbDir to private void Decompress which should then create the subfolders and decompress the zip files.
How can I resolve this issue?
Below is the code I am using.
namespace HealthCheckScanner
{
public partial class Form1 : Form
{
string sbDir = null;
public Form1()
{
InitializeComponent();
}
//Get the zip files parent directory
private void sbFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
sbDir = Convert.ToString(folderBrowserDialog1.SelectedPath);
}
}
//Uncompress all zip files in their own directory using zip file name in the parent directory
private void Decompress(DirectoryInfo sbDir)
{
foreach (FileInfo file in sbDir.GetFiles())
{
string fileName = (Regex.Replace(sbDir + file.Name, ".Zip", ""));
string filePath = Convert.ToString(sbDir);
ZipFile.ExtractToDirectory(fileName, filePath);
}
}
}
}
I was able to find a solution using the following code
//Get the zip files parent directory
private void sbFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
sbDir = Convert.ToString(folderBrowserDialog1.SelectedPath);
}
DirectoryInfo directory = new DirectoryInfo(#sbDir);
foreach (FileInfo file in directory.GetFiles())
{
string pathA = file.Name;
int index = pathA.IndexOf(".");
if (index > 0)
pathA = pathA.Substring(0, index);
string filePath = sbDir + #"\" + pathA;
string fileName = sbDir + #"\" + file.Name;
//Uncompress all zip files in their own directory using zip file name in the parent directory
ZipFile.ExtractToDirectory(fileName, filePath);
}

Opening a file dialog , taking the file path in a var

I am able to open a file dialog, now i want to know how do i get the path of the file in var variable something like
OpenFileDialog fd1 = new OpenFileDialog();
fd1.InitialDirectory = "c:\\";
fd1.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
fd1.FilterIndex = 2;
fd1.RestoreDirectory = true;
so i want in my var something like
var path = #"c:\abc.pdf";
Is it possible
Here it is:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var path = openFileDialog1.FileName;
}
This way you'll get your path to file like:
C:\folder1\folder2\fffffffff...\abc.pdf
Update:
you'll change your "var" into "string" and you'll make your path variable a global variable. here is an example:
private string path;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
path = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(path);
}
you don't need to make your variable a public because you are in the same class!!!
Update:
Think that this will do
AxAcroPDF1.src = path;
The Process.Start should launch a new process to open the pdf file with default client that is Adobe Reader.
You can prompt user with filedialog to get you a file path.
If you want to get some of specific folders you can try
String PersonalFolder =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
Environment have alot of folders that are specific for machine.
hope it helps

Best way to create a folder and upload a image to that folder in ASP.NET?

Any code examples on how i must go about creating a folder say "pics" in my root and then upload a images from the file upload control in into that "pics" folder?
If you don't want to give me all the code, i will be happy with a nice link also to show me how this will be done in VB.NET (C# is also ok).
Try/Catch is on you :)
public void EnsureDirectoriesExist()
{
// if the \pix directory doesn't exist - create it.
if (!System.IO.Directory.Exists(Server.MapPath(#"~/pix/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"~/pix/"));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".jpg")
{
// create posted file
// make sure we have a place for the file in the directory structure
EnsureDirectoriesExist();
String filePath = Server.MapPath(#"~/pix/" + FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
}
else
{
lblMessage.Text = "Not a jpg file";
}
}
here is how I would do this.
protected void OnUpload_Click(object sender, EventArgs e)
{
var path = Server.MapPath("~/pics");
var directory = new DirectoryInfo(path);
if (directory.Exists == false)
{
directory.Create();
}
var file = Path.Combine(path, upload.FileName);
upload.SaveAs(file);
}
Create Folder inside the Folder and upload Files
DirectoryInfo info = new DirectoryInfo(Server.MapPath(string.Format("~/FolderName/") + txtNewmrNo.Text)); //Creating SubFolder inside the Folder with Name(which is provide by User).
string directoryPath = info+"/".ToString();
if (!info.Exists) //Checking If Not Exist.
{
info.Create();
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++) //Checking how many files in File Upload control.
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(directoryPath + Path.GetFileName(hpf.FileName)); //Uploading Multiple Files into newly created Folder (One by One).
}
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('This Folder already Created.');", true);
}

Categories

Resources