Detectings Files before extract using Iconic zip - c#

I am using Iconic.zip as a way of extracting files on a server but its for a theme pack. And I want to be able to check if a file exists in the zip file before unziping is this possible with the libary.
I am using the following code which works to upload and extract the files.
if (fileUploadZipFiles.HasFile)
{
string uploadedZipFile = Path.GetFileName(fileUploadZipFiles.PostedFile.FileName);
string zipFileLocation = Server.MapPath("~/Themes/" + uploadedZipFile);
fileUploadZipFiles.SaveAs(zipFileLocation);
ZipFile zipFileToExtract = ZipFile.Read(zipFileLocation);
zipFileToExtract.ExtractAll(Server.MapPath("~/Themes/" + txtFolderName.Text.ToString()), ExtractExistingFileAction.DoNotOverwrite);
gridviewExtractedFiles.DataSource = zipFileToExtract.Entries;
gridviewExtractedFiles.DataBind();
lblMessage.Text = "Zip file extracted successfully and containes following files";
}
The second part of this question is that I am using master pages for my themes how would i go about setting the active theme to the one the user wants to make acitve. I am sure I have to have my own base page.
I found the anser to my first part of question was to use the following.
if (fileUploadZipFiles.HasFile)
{
string uploadedZipFile = Path.GetFileName(fileUploadZipFiles.PostedFile.FileName);
string zipFileLocation = Server.MapPath("~/Themes/" + uploadedZipFile);
fileUploadZipFiles.SaveAs(zipFileLocation);
ZipFile zipFileToExtract = ZipFile.Read(zipFileLocation);
var result = zipFileToExtract.Any(entry => entry.FileName.EndsWith("site.master"));
if (result == true)
{
zipFileToExtract.ExtractAll(Server.MapPath("~/Themes/" + txtFolderName.Text.ToString()), ExtractExistingFileAction.DoNotOverwrite);
gridviewExtractedFiles.DataSource = zipFileToExtract.Entries;
gridviewExtractedFiles.DataBind();
lblMessage.Text = "Zip file extracted successfully and containes following files";
}
else
lblMessage.Text = "Not a vlaid theme file.";
}
As suggested here is the answer i used linq to check the existence of the file.
protected void btnExtractZipFiles_Click(object sender, EventArgs e)
{
if (txtFolderName.Text == "")
{
lblMessage.Text = "A Folder Name must be specified";
}else
if (fileUploadZipFiles.HasFile)
{
string uploadedZipFile = Path.GetFileName(fileUploadZipFiles.PostedFile.FileName);
string zipFileLocation = Server.MapPath("~/Themes/" + uploadedZipFile);
fileUploadZipFiles.SaveAs(zipFileLocation);
ZipFile zipFileToExtract = ZipFile.Read(zipFileLocation);
var result = zipFileToExtract.Any(entry => entry.FileName.EndsWith("default.Master"));
if (result == true)
{
zipFileToExtract.ExtractAll(Server.MapPath("~/Themes/" + txtFolderName.Text.ToString()), ExtractExistingFileAction.DoNotOverwrite);
gridviewExtractedFiles.DataSource = zipFileToExtract.Entries;
gridviewExtractedFiles.DataBind();
lblMessage.Text = "Zip file extracted successfully and containes following files";
SetConfiguration(); //parse the configuration file
}
else
lblMessage.Text = "Not a vlaid theme file.";
}
}

Related

Return network name from file path [duplicate]

This question already has answers here:
How do I determine a mapped drive's actual path?
(14 answers)
Closed 2 years ago.
I have ran into an issue where by when the user adds a file directory to my project the link is stored as their own mapped drive. For example;
C:\Location\Location
However, some users may have the C: drive on the server mapped as M: for example. Thus are unable to locate the file.
What I would like to do is replace this with the actual server name, ie
\\ArtServer\
I know that I could achieve this by replacing the opening part of the string, however if more servers are added in the future then this will obviously fallover in a huge mess. Currently the user grabs the file path using a standard get file dialogue;
public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = #"This PC")
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = filter;
fileDialog.FilterIndex = 1;
fileDialog.Multiselect = false;
fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : #"This PC";
if (fileDialog.ShowDialog() == true)
{
return fileDialog.FileName;
}
else
{
return null;
}
}
Is there anyway I can achieve this with what I currently have?
Thank you to #ADyson for all of your help. I decided to use an answer provided by ibram from the thread linked above. For anyone else who has the same issue I have posted what I had done;
public static string GetUNCPath(string path)
{
if (path.StartsWith(#"\\"))
{
return path;
}
ManagementObject mo = new ManagementObject();
mo.Path = new ManagementPath(String.Format("Win32_LogicalDisk='{0}'", path));
// DriveType 4 = Network Drive
if (Convert.ToUInt32(mo["DriveType"]) == 4)
{
return Convert.ToString(mo["ProviderName"]);
}
else
{
return path;
}
}
public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = #"This PC")
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = filter;
fileDialog.FilterIndex = 1;
fileDialog.Multiselect = false;
fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : #"This PC";
if (fileDialog.ShowDialog() == true)
{
// Split the file directory to gain root path
// Use GetUNCPath to convert root path to server name
string s = fileDialog.FileName;
int index = s.IndexOf(':') + 1;
string rootPath = GetUNCPath(s.Substring(0, index));
string directory = s.Substring(index);
return rootPath + directory;
}
else
{
return null;
}
}

insert relative path for saving a zip file in asp.net

I wrote this function for creating a zip archive
protected void ImageButton_documenti_Click(object sender, ImageClickEventArgs e)
{
string path_cartella = #"d:\work\project1\temp\document";
string path_cartella_zip = #"d:\work\project1\temp\document_zip\";
path_cartella_zip = path_cartella_zip + "zip_documenti_al_" + System.DateTime.Now.ToString("ddMMyyyy") + ".zip";
//al click dell'immagine creo un file zip contenente tutte le cartelle dei documenti
using (ZipFile zip = new ZipFile())
{
try
{
zip.AddDirectory(path_cartella);
zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G");
zip.Save(path_cartella_zip);
operazione_ok.Visible = true;
operazione_ok.InnerText = "Procedura di zip attivata.";
}
catch (Exception errore)
{
elenco_errori.Visible = true;
elenco_errori.InnerText = errore.Message;
}
}
}
this function work fine in local but on my web server I don't know the absolute path and I want to change the "string_path_cartella" and "string_path_cartella_zip" for saving document with a relative path in "temp/document" folder
Try this:
string path_cartella = Server.MapPath("~/temp/document");
string path_cartella_zip = Server.MapPath("~/temp/document_zip");
Reference: http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath%28v=vs.110%29.aspx

Confusion in reading file using FolderBrowserDialog

which i used earlier (FileuploadControl tool used)
inside button click method
if (FileUploadControl.HasFile)
{
filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
string lines;
string root = Server.MapPath("~/");
string Template = root + filename;
using (StreamReader reader = new StreamReader(Template))
{
while ((lines = reader.ReadLine()) != null)
list.Add(lines); // Add to list.
}
//file is now in list
//MORE IMPORTANT CODE
}
But now I am just using FolderDialog
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.ShowNewFolderButton = true;
DialogResult result = folderDialog.ShowDialog();
if (result == DialogResult.OK) {
textBox8.Text = folderDialog.SelectedPath;
Environment.SpecialFolder root = folderDialog.RootFolder
//...
}
How can i read the file so that i can only use the FolderBrowserDialog to read an entire file and extract data?
I guess you are working in Windows Forms now if you are using FolderDialog.
You should use better OpenFileDialog if you want the user to check a FILE, not a Folder.
You can read the file using System.IO classes once you have the path.
If the file is text for example you can do:
string FinalPath = OpenFileDialog.FileName;
string Text= System.IO.File.ReadAllText(FinalPath);
you can also read the file into byte()
byte[] file = System.IO.File.ReadAllBytes(FinalPath);

C# is there a limit to number of selected files in Open File Dialog

I've got a C# windows forms application where I load XML files and CGM graphics files into my application from an Open File browser. I seem to be able to select a couple of hundred at a time and it works without fault, but any more and a dialog box pops up telling me it can't find file such and such, but only gives half the file name. I'm assuming this is due to a limit on the amount of files that can be selected / processed in one go through the open file dialog.
Does anybody know what that number is, and is there a way around it if i have more than that limit to select at once?
I'm effectively 'importing' the files into my application, whereby using a foreach loop the selected files get moved to another folder, and the application writes to an XML file with all the file names of the files imported (as well as other data on the files).
Below is the entire 'import' method
private void addFilesToCSDBToolStripMenuItem_Click(object sender, EventArgs e)
{
int DMsimported = 0;
int graphicsImported = 0;
if (projectName == "")
{
MessageBox.Show("Please open a project first", "DAWS");
return;
}
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
MessageBox.Show("This process may take several minutes depending on the number of imports", "DAWS");
Application.UseWaitCursor = true;
foreach (string file in openFileDialog1.FileNames)
{
string fileName = Path.GetFileNameWithoutExtension(file); //Gets just the name from the file path
string ext = Path.GetExtension(file.ToLower());
if (ext != ".CGM" && ext != ".cgm")
{
bool exists = xmlFileWriter.checkIfFIleExists(fileName + ext);
if (exists != true)
{
xmlFileWriter.writeDatatoXML(file);
File.Move(file, CSDBpath + projectName + "\\CheckedIN\\" + fileName + ext);
DMsimported = DMsimported + 1;
}
else
{
MessageBox.Show(fileName + " already exists in the CSDB. This file will be skipped.", "DAWS");
}
}
else
{
if (File.Exists(CSDBpath + projectName + "\\Graphics\\" + fileName + ext))
{
if (Properties.Settings.Default.OverwriteGraphics == true)
{
File.SetAttributes(CSDBpath + projectName + "\\Graphics\\" + fileName + ext, FileAttributes.Normal); // need this line in order to set the file attributes. Exception thrown otherwise when system tries to overwrite the file.
File.Delete(CSDBpath + projectName + "\\Graphics\\" + fileName + ext);
File.Copy(file, CSDBpath + projectName + "\\Graphics\\" + fileName + ext); //need to give the option as to whether to delete the existing file or skipp.
}
else
{
MessageBox.Show(fileName + " already exists in the CSDB. This file will be skipped. To enable overwriting tick the checkbox in Preferences", "DAWS");
}
}
else
{
File.Copy(file, CSDBpath + projectName + "\\Graphics\\" + fileName + ext);
}
graphicsImported = graphicsImported + 1;
}
}
Application.UseWaitCursor = false;
buildAllListViews();
copyCGMfilesToDirectories();
if (DMsimported > 0)
{
MessageBox.Show(DMsimported.ToString() + " DM files successfully imported into the CSDB", "DAWS");
}
if (graphicsImported > 0)
{
MessageBox.Show(graphicsImported.ToString() + " graphic files successfully imported into the CSDB", "DAWS");
}
if (graphicsImported == 0 && DMsimported == 0)
{
MessageBox.Show("No files imported", "DAWS");
}
updateMainFilesList();
}
}
According to this article, you will receive a "Too many files selected" error message when you use the OpenFileDialog control to select more than 200 files.
Just tested in .NET 4.5, no problem with 5000 files, so it looks like it depends on .net framework/os version (I've used long enough file names, just to be sure, that it does not depend on some old windows constraint, like max length of all file names is 65536 or 32768):
var directory = #"c:\test\test";
Directory.CreateDirectory(directory);
for (int i = 0; i < 5000; i++)
{
var path = Path.Combine(directory, i.ToString() + new string('a', 200));
File.WriteAllText(path, "");
}
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var fileCount = openFileDialog1.FileNames;
var lastFileName = openFileDialog1.FileNames[4999];
}
In .NET Framework 1.1, for the OpenFileDialog.Multiselect Property:
There is a hard-coded limit of 200 files that can be opened with the
Open File dialog box. For more information about this limitation, see
article 820631, "PRB: 'Too Many Files Selected' Error Message Occurs
When You Use the OpenFileDialog Control", in the Microsoft Knowledge
Base at http://support.microsoft.com.
When you have to work with such a large number of files, maybe it makes more sense to select only the folder (even more reasonable if you select all the files in the folder, if this is your case). Try using the FolderBrowserDialog Class:
var folderBrowserDialog = new FolderBrowserDialog();
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
var fi = new DirectoryInfo(folderBrowserDialog.SelectedPath);
// here you get the files collection
var files = fi.GetFiles();
}
Try:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
openFileDialog1.Multiselect = false;
var fileCount = openFileDialog1.FileNames;
var lastFileName = openFileDialog1.FileNames[4999];
}

Showing the dialog of the file already existence at the location

I have an application in which the user interacts with a database and prepares a report of what he needs. The item prices are listed in the database. Once he chooses the items then he generates a report in Excel format. When he hits the Generate a Report button, he is asked where to save the report. These are all good. The problem is that when he saves the report and hits the Generate A Report button, he is able to save the same file with the same name at the same location when a file of the same name exists at that location. It basically replaces the old one. I wrote a code to check for the file if it exists and it works but the problem is that it does not appear at the instant when you are saving the file. It appears before. What I want is when I try to save the file at any location, it gives me at that instant that "The file exists and do you want to replace it with it", more like Windows dialog when you try to save a word document into a location where there is a document with the same name.
If anyone needs any clarifications please comment, I am online most of the times.
Here is the code
private void btnRunReport_Click(object sender, EventArgs e)
{
if (cmbReportsList.SelectedIndex != -1)
{
_qry = new QueryMgt();
OpenProjectDb();
string _sProjectName = (dbManager.ExecuteScalar(CommandType.Text, _qry.GetProjectFileName())).ToString();
CloseProjectDb();
if (cmbReportsList.SelectedIndex == 0)
{
SaveFile.Filter = "excel 2007 (*.xlsx)|*.xlsx";
SaveFile.DefaultExt = "xlsx";
SaveFile.FileName = _sProjectName + " Report1";
strFilepath = System.IO.Path.GetFullPath(SaveFile.FileName);
if (SaveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.Text = System.IO.Path.GetFileName(SaveFile.FileName);
strFilepath = System.IO.Path.GetFullPath(SaveFile.FileName);
if (strFilepath.Length > 218) { strFilepath = StringMgt.Left(strFilepath, 218); }
btnRunReport.Visible = false;
bg1804Rpt.RunWorkerAsync();
Application.DoEvents();
}
}
else if (cmbReportsList.SelectedIndex == 1)
{
SaveFile.FileName = _sProjectName + " Report2";
SaveFile.Filter = "excel 2007 (*.xlsx)|*.xlsx";
SaveFile.DefaultExt = "xlsx";
if (SaveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//SaveFile.FileName = "Report2";
this.Text = System.IO.Path.GetFileName(SaveFile.FileName);
strFilepath = System.IO.Path.GetFullPath(SaveFile.FileName);
if (strFilepath.Length > 218) { strFilepath = StringMgt.Left(strFilepath, 218); }
btnRunReport.Visible = false;
bgMCRpt.RunWorkerAsync();
Application.DoEvents();
}
}
else if (cmbReportsList.SelectedIndex == 2)
{
_qry = new QueryMgt();
_formula = new FormulaMgt();
string sSQL;
string chrCountryName = "";
OpenProjectDb();
OpenTableDb();
DataSet dsProjectSpec;
DataSet dsCountry;
sSQL = _qry.GetProjectSpec().ToString();
dsProjectSpec = dbManager.ExecuteDataSet(CommandType.Text, sSQL);
sSQL = _qry.GetCountry().ToString();
dsCountry = dbManagerTable.ExecuteDataSet(CommandType.Text, sSQL);
foreach (DataRow row in dsCountry.Tables[0].Select("pk_lngCountryID ='" + dsProjectSpec.Tables[0].Rows[0]["lngCountryId"] + "'"))
{
chrCountryName = row["chrCountryName"].ToString();
break;
}
SaveFile.FileName = _sProjectName + " Report3";
SaveFile.Filter = "excel 2007 (*.xlsx)|*.xlsx";
SaveFile.DefaultExt = "xlsx";
// SaveFile.Filter = "Microsoft Office Excel Worksheet (*.xlsx)|*.xls|All files (*.*)|*.*";
if (SaveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//SaveFile.FileName = "Report3";
this.Text = System.IO.Path.GetFileName(SaveFile.FileName);
strFilepath = System.IO.Path.GetFullPath(SaveFile.FileName);
if (strFilepath.Length > 218) { strFilepath = StringMgt.Left(strFilepath, 218); }
btnRunReport.Visible = false;
bgMDRpt.RunWorkerAsync();
Application.DoEvents();
}
}
}
else if (cmbReportsList.SelectedIndex == -1)
{
MessageBox.Show("Please select any report", "Info", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
You have not provided any code so I am left wondering.
But are you using SaveFileDialog? If not, I highly suggest it. It provides that functionality.
SaveFileDialog sfd = new SaveFileDialog();
sfd.OverwritePrompt = true;
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Do Something
// Access the filename they choose via: ofd.FileName
}
And if the user selects a file that exists, they will be asked if they are sure they want to overwrite it.
SaveFileDialog also has several properties you can define. Such as the Filter property for defining acceptable file extensions.

Categories