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);
}
Related
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);
}
}
}
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.");
}
}
}
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);
}
I have a TextBox (txtDocUpload) and a Button. On the clicking of that button, an upload dialogue is opening and after uploading a file I have to save it in a particular folder.
For opening the upload dialogue
private void txtBtnUpload_Click_1(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
//openFileDialog.DefaultExt = ".txt";
Nullable<bool> result = openFileDialog.ShowDialog();
if (result == true)
{
filename = openFileDialog.FileName;
txtDocUpload.Text = System.IO.Path.GetFileName(filename);
}
}
Clicking save button I have to save, and the code ("File1"is the location where i want to save the file).
string urlpath = "WoDocs";
var path = #"~\" + urlpath + #"\" + WOMaintenance.GetAddressId.IDWorkOrderDetail;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var ext = System.IO.Path.GetExtension(txtDocUpload.Text);
var pathURL=txtDocDescription.Text+ext;
var file1 = System.IO.Path.Combine(path,txtDocDescription.Text + ext);
//docFile1.SaveAs(file1);
Here is a brief example:
private void CopyAFile()
{
var source = new OpenFileDialog();
if (source.ShowDialog().GetValueOrDefault())
{
var dest = new SaveFileDialog();
if (dest.ShowDialog().GetValueOrDefault())
{
File.Copy(source.FileName, dest.FileName);
}
}
}
This should demonstrate that File.Copy does work when you have access to the source and destination locations.
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);
}