I am using Windows form application. In my application I am using FolderBrowserDialog, textbox1 and two buttons. In my textbox I am passing folder. From folder it will select particular file type. After getting such file type I need to convert it using ZipFile i.e. Iconic.zip. After retrieving particular file type it is showing me error of FileNotfound. For testing purpose I tried to display retrived file to listbox and it is working well. But when I am calling via ZipFile it is giving me error, can't figure out what error is.
namespace WinDataStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
string[] extensions = { ".xml",".ddg" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*",SearchOption.AllDirectories)
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
// listBox1.Items.AddRange(dizin);
using (ZipFile zip = new ZipFile())
{
zip.AddFile("dizin", "files");
zip.Save("z.zip");
}
}
}
}
You can't pass a variable as a string like this:
string[] dizin = ...;
zip.AddFile("dizin", "files");
Instead use it like this:
zip.AddFile(dizin, "files");
Or more likely you need to loop:
foreach(var file in dizin)
{
zip.AddFile(file, "files");
}
Or if you are using Ionic Zip Library use the AddFiles method:
zip.AddFiles(dizin, "files");
This below code solved my problem
using (ZipFile zip = new ZipFile())
{
foreach(var file in dizin)
{
zip.AddFile(file);
}
zip.Save("z.zip");
}
Related
As you can see in code, folders are created during move file button. my question is that how to moves files in that particular folders, I have tens of millions of files and want to moves in that particulars. I am new in c#.
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace File2Folders
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> fileName = null;
List<string> fileNames = null;
private void btn_browse_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Clear();
fileName = Directory.GetFiles(fbd.SelectedPath).ToList();
fileNames = fileName.Select(item => Path.GetFileNameWithoutExtension(item).Substring(1, 4)).OrderBy(n=>n).ToList();
listBox1.DataSource = fileName.Select(f => Path.GetFileName(f)).ToList();
listBox2.DataSource = fileNames;
}
}
}
private void btn_move_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog fbd = new FolderBrowserDialog())
{
if (fbd.ShowDialog() == DialogResult.OK)
{
fileNames.ForEach(item => Directory.CreateDirectory(Path.Combine(fbd.SelectedPath, item)));
}
Try to use this fuction that I use sometimes.
bool FileCopyPasteRename(string source, string destination, string renameTo)
{
bool res = false;
string renameDestination = Path.Combine(destination, renameTo.ToLower());
try
{
if (File.Exists(source))
{
File.Copy(source, renameDestination, true);
}
}
catch (Exception ex)
{
//cath error ex.Message
}
return res;
}
Once its a bool function, you can check if returns true and the delete source file.
To move a file you can use method Move in File. It takes as parameter the path of the file you want to move and the destination including and the file name
here is an example
string filePath = #"C:\Users\HP\source\repos\ConsoleApp1\ConsoleApp1\fileToMove.txt";
string destination = #"C:\Users\HP\source\repos\ConsoleApp1\ConsoleApp1\Dummy\fileToMove.txt";
try
{
File.Move(filePath, destination);
}
catch (Exception e)
{
Console.WriteLine("We coudnt move the file becouse of: " + e.Message);
}
For more https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?view=net-6.0
This question already has answers here:
Can you call Directory.GetFiles() with multiple filters?
(27 answers)
Closed 9 years ago.
I have a program which gives random files. It is simple but I'm quite new to this.
Im having trouble with creating fileinfo list of files. I added a contextmenustrip which has multiple choose of file genre (e.g: video files, text files..)
I wanted to define string array with cntxtmnustrp. and want it make new array and combine with previous. But it didnt work. Should I create a arraylist and add each list to this?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random r = new Random();
string path1;
DirectoryInfo dif;
// List<FileInfo> files;
FileInfo[] files;
FileInfo[] newfiles;
int randomchoose;
int fok;
int kok, pd;
string[] filetypes;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog hoho = new FolderBrowserDialog(); // yeni dosya yeri
hoho.ShowNewFolderButton = true;
if (hoho.ShowDialog() == DialogResult.OK)
{
path1 = hoho.SelectedPath;
textBox1.Text = path1;
dif = new DirectoryInfo(path1);
foreach (string ft in filetypes)
{
files = dif.GetFiles("*.ft", SearchOption.AllDirectories);
//files.AddRange(dif.GetFiles(string.Format("*.{0}", ft), SearchOption.AllDirectories));
newfiles = newfiles.Concat(files);
}
//pd = liste.Length;
pd = files.Length;
kok = pd;
}
}
}
private void button1_Click_1(object sender, EventArgs e)
{
listBox1.Sorted = true;
}
private void cesit_Click(object sender, EventArgs e)
{
//contextMenuStrip1.Show();
contextMenuStrip1.Show(this.PointToScreen(cesit.Location));
}
private void videoFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
filetypes = new string[2] { "txt", "png" };
}
private void musicFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
//tur = ".png";
//textBox4.Text = tur;
}
private void textFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
}
Assuming I understand what you mean, I'd make the files array into a List, by replacing:
FileInfo[] files;
with:
List<FileInfo> files;
That means you'd change:
files = dif.GetFiles("*.ft", SearchOption.AllDirectories);
to:
files.AddRange(dif.GetFiles(string.Format("*.{0}", ft) SearchOption.AllDirectories));
You can then get rid of the list concatenation:
newfiles = newfiles.Concat(files);
I wrote a program, code seems working but it is not working. It gives IO exception was unhandled error. Some guys say me , you should delete something because program try to use same file at the same time. Please help me!!
namespace App1508
{
public partial class Form2 : Form
{
string goodDir = "C:\\GOOD\\";
string badDir = "C:\\BAD\\";
string fromDir = "C:\\DENEME\\";
List<Image> images = null;
int index = -1;
FileInfo[] finfos = null;
public Form2()
{
InitializeComponent();
DirectoryInfo di = new DirectoryInfo(#"C:\DENEME");
finfos = di.GetFiles("*.jpg",SearchOption.TopDirectoryOnly);
images = new List<Image>();
foreach (FileInfo fi in finfos)
{
images.Add(Image.FromFile(fi.FullName));
}
}
private void button1_Click(object sender, EventArgs e)
{
finfos[index].MoveTo(Path.Combine("C:\\GOOD", finfos[index].Name));
}
private void pictureBox1_Click(object sender, EventArgs e)
{
index++;
if (index < 0 || index >= images.Count)
index = 0;
pictureBox1.Image = images[index];
}
private void button2_Click(object sender, EventArgs e)
{
finfos[index].MoveTo(Path.Combine("C:\\BAD", finfos[index].Name));
}
}
}
This is the problem:
foreach (FileInfo fi in finfos)
{
images.Add(Image.FromFile(fi.FullName));
}
Image.FromFile will open a file handle, and won't close it until you dispose of the image. You're trying to move the file without disposing of the image which has that file open first.
I suspect if you dispose of the relevant image in your button1_Click and button2_Click methods (being aware that if it's showing in the PictureBox you'll need to remove it from there first) you'll find it works.
Ref:
http://support.microsoft.com/?id=814675
using Telerik.WinControls.Data;
using Telerik.WinControls.UI.Export;
namespace Directory
{
public partial class radForm : Form
{
public radForm()
{
InitializeComponent();
}
private void radForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'directoryDataSet.DirDetails' table. You can move, or remove it, as needed.
this.dirDetailsTableAdapter.Fill(this.directoryDataSet.DirDetails);
}
// Button click
private void button1_Click(object sender, EventArgs e)
{
ExportToPDF exporter = new ExportToPDF(this.radGridView1);
//The FileExtension property allows you to change the default (*.pdf) file extension of the exported file
exporter.FileExtension = "pdf";
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
// This to make the grid fits to the PDF page width
exporter.FitToPageWidth = true;
// Exporting data to PDF is done through the RunExport method of ExportToPDF object
string fileName = "c:\\Directory-information.pdf";
exporter.RunExport(fileName);
}
}
}
Some how Im missing something here and my gridview isn't exporting into pdf and no file creation takes place.
private void button1_Click(object sender, EventArgs e)
{
ExportToPDF exporter = new ExportToPDF(this.radGridView1);
exporter.FileExtension = "pdf";
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
exporter.ExportVisualSettings = true;
exporter.PageTitle = "Directory Details";
exporter.FitToPageWidth = true;
string fileName = "c:\\Directory-information.pdf";
exporter.RunExport(fileName);
MessageBox.Show("Pdf file created , you can find the file c:\\Directory-informations.pdf");
}
I am trying to open a file which a user can set. In other words it will never be a set path or file. so when the user has selected the file they want to open this button below will open it. I have declared l1 and p1 as public strings.
public void button4_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
l1 = Path.GetFileName(openFileDialog1.FileName);
p1 = System.IO.Path.GetDirectoryName(openFileDialog1.FileName);
}
public void button2_Click(object sender, EventArgs e)
{
//p1 = directory path for example "C:\\documents and settings\documents"
//l1 = filename
Process.Start(p1+l1);
}
So just to review I want to open up the file just using the directory path and filename. Is this possible? I can just have p1 there and it will open an explorer showing me that directory. Thank you for looking.
Yes it will work, but I would recommend you update your code this instead:
var path = Path.Combine(p1, l1);
Process.Start(path);
You shouldn't use string concatenation to combine a directory and filename. In your case the resulting string will look like this:
C:\documents and settings\documentsfilename
^^
this is wrong
Instead use Path.Combine.
string path = Path.Combine(p1, l1);
Process.Start(path);
Why don't you simply do this: -
public void button4_Click(object sender, EventArgs e)
{
string fileNameWithPath;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
fileNameWithPath = openFileDialog1.FileName;
}
}
public void button2_Click(object sender, EventArgs e)
{
Process.Start(fileNameWithPath);
}