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

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

Related

Uploading multiple files to firbase storage | Unity

Hey I'm trying to upload all files located in a folder to firestore storage.
However im quite new to c# and unity.
I have the following code to upload a file located in the folder.
if(Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead)){
Debug.Log("Permissions Found");
var Directory_path = ("SparseSpatialMap/Copia.meta");
var path = (Application.persistentDataPath + "/" + Directory_path);
//Firestore Reference
storage = FirebaseStorage.DefaultInstance;
storageReference = storage.GetReferenceFromUrl("gs://houdini-ac884.appspot.com");
StreamReader stream = new StreamReader(path);
// Create a reference to the file you want to upload
StorageReference riversRef = storageReference.Child("uploads/newFile.meta");
// Upload the file to the path "uploads/newFile.meta"
riversRef.PutStreamAsync(stream.BaseStream)
.ContinueWith((task) => {
if (task.IsFaulted || task.IsCanceled) {
Debug.Log(task.Exception.ToString());
// Uh-oh, an error occurred!
}
else {
// Metadata contains file metadata such as size, content-type, and download URL.
StorageMetadata metadata = task.Result;
string md5Hash = metadata.Md5Hash;
Debug.Log("Finished uploading...");
Debug.Log("md5 hash = " + md5Hash);
}
});
} else {
Debug.Log("No Permissions");
Permission.RequestUserPermission(Permission.ExternalStorageRead);
return;
}
The file i uploaded with success is located here " /storage/emulated/0/Android/data/estg.easy.ar/files/SparseSpatialMap/Copia.meta "
I want to upload all files in the /SparseSpatialMap direcory
What you’re looking for is a way to get all file names, or paths. Try importing System.IO if you have already then you can use Directory.GetFiles(path) replacing path with the folder directory. Then you should have an array of strings representing each file.
For anyone looking for the solution this was how i did it.
got all files via their folder with DirectoryInfo and uploaded each individually using it's the respective name
if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead)){ //Cria ficheiros em branco (Ou por nao ter acesso a um ficheiro que está a ser usado ou por ser Asyncrono)
Debug.Log("Permissions Found");
DirectoryInfo d = new DirectoryInfo(Application.persistentDataPath + "/SparseSpatialMap");
FileInfo[] Files = d.GetFiles("*.meta"); //Getting meta files
string str = "";
foreach(FileInfo file in Files )
{
str = str + ", " + file.Name;
var Directory_path = ("SparseSpatialMap/" + file.Name);
var path = (Application.persistentDataPath + "/" + Directory_path);
//Firestore Reference
storage = FirebaseStorage.DefaultInstance;
storageReference = storage.GetReferenceFromUrl("gs://houdini-ac884.appspot.com");
// File located on disk
string localFile = path.ToString();
StreamReader stream = new StreamReader(path);
// Create a reference to the file you want to upload
StorageReference riversRef = storageReference.Child("uploads/"+ file.Name);
// Upload the file to the path "uploads/newFile.meta"
riversRef.PutStreamAsync(stream.BaseStream)
.ContinueWith((task) => {
if (task.IsFaulted || task.IsCanceled) {
Debug.Log(task.Exception.ToString());
// Uh-oh, an error occurred!
}
else {
// Metadata contains file metadata such as size, content-type, and download URL.
StorageMetadata metadata = task.Result;
string md5Hash = metadata.Md5Hash;
Debug.Log("Finished uploading...");
Debug.Log("md5 hash = " + md5Hash);
}
});
}
Debug.Log(str);
} else {
Debug.Log("No Permissions");
Permission.RequestUserPermission(Permission.ExternalStorageRead);
return;
}

How to copy images and videos file asynchronous in c# WPF add add to listbox item

How to copy images and videos file asynchronous in c# WPF?
I am already using this for copying txt files and its working, but if I use it for copying images or videos, the result does not open or crash.
Any Idea what could be wrong? This is my code
private async void btnUpdate_Click(object sender, RoutedEventArgs e)
{
string x2 = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
DirectoryInfo dinfo = new DirectoryInfo(x2);
FileInfo[] Files = dinfo.GetFiles("*.txt");
int jml = 0;
foreach (FileInfo file in Files)
{
string fileNoExtension = file.Name.Replace(".txt", "");
string fileName2 = x2 + #"\Data\" + file.Name;
using (StreamReader SourceReader = File.OpenText(#"Data\" + file.Name))
{
using (StreamWriter DestinationWriter = File.CreateText(x2 + #"\Data\" + file.Name))
{
await CopyFilesAsync(SourceReader, DestinationWriter);
}
}
lbxHasil.Items.Add(file.Name);
jml = jml + 1;
}
MessageBox.Show("Success add " + jml.ToString() + " New Songs!!!");
btnUpdate.IsEnabled = false;
lbxAwal.Items.Clear();
}
You need to use File.OpenRead and File.OpenWrite so it's treated as binary.
Or File.Create as JohnnyMopp said.
Alternatively if there's no additional processing File.Copy
It depends on what you need to do but your problems are related to treating it as text not binary.

Detectings Files before extract using Iconic zip

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.";
}
}

Files on the server are overwritten with files of the same name

I am trying to upload files with same names to the server using GUID, but its not working and is still replacing the old files, can anybody help me by telling where I am making the mistake?
here is y code to upload:
protected void btnAddExpenditure_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
//check file Extension & Size
int filesize = FileUpload1.PostedFile.ContentLength;
if (filesize > (20 * 1024))
{
Label1.Text = "Please upload a zip or a pdf file";
}
string fileextention = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileextention.ToLower() != ".zip" && fileextention.ToLower() != ".pdf")
{
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "Please upload a zip or a pdf file";
}
else
{
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//save file to disk
FileUpload1.SaveAs(Server.MapPath("Reciepts/" + ReceiptFileName));
}
string FileName = FileUpload1.PostedFile.FileName;
if (File.Exists(FileName))
{
FileName = Guid.NewGuid() + FileName;
}
...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Here's your problem. You're creating a new string variable that holds the file name (FileName). If it exists, you modify FileName with a new GUID. But at the very end...
string ReceiptFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
you're still using the original FileUpload1.PostedFile.FileName. This should be changed to
string ReceiptFileName = Path.GetFileName(FileName);
EDIT: Reading through the code again, I think you may have other problems as well. Assuming that FileUpload1.PostedFile.FileName is a full path (i.e. C:\Folder\File.txt), then
FileName = Guid.NewGuid() + FileName;
would result in something like 123-4321-GUIDC:\Folder\File.txt
I doubt that's what you want. You might want to flip that around
FileName = FileName + Guid.NewGuid();

Upload File attached to FileUpload Control to FTP C#

I am trying to upload a file that is attached to a FileUpload control to a folder that is created in FTP. The Folder is getting created without issue but I can't seem to upload the file.
It seems as though my filepath to the source file is incorrect in the line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); I have tried multiple variations of the file path but cannot seem to get the file uploaded.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
string ftphost = WebConfigurationManager.AppSettings["myHost"].ToString();
string u = WebConfigurationManager.AppSettings["u"].ToString();
string p = WebConfigurationManager.AppSettings["p"].ToString();
string nameToGiveFolder = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().LastIndexOf("."));
string ftpfullpath = "ftp://" + ftphost + "/" + nameToGiveFolder;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.Credentials = new NetworkCredential(u, p);
FtpWebResponse CreateFolderResponse = (FtpWebResponse)ftp.GetResponse();
if (FileUpload1.HasFile)
{
try
{
Label1.Text = "Has File";
String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder);
FileUpload1.SaveAs(filePath);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
else
{
Label1.Text = "No File";
}
}
Use Path.GetFileNameWithoutExtension(). to get the file name
FileUpload1.SaveAs(Server.MapPath(string.Format("~/{0}/{1}", Path.GetFileNameWithoutExtension(FileUpload1.FileName), FileUpload1.FileName)));
Note that you need to give the file name as well, if the file name is abc.jpg, above code try to create folder under your root of the web side called abc and save the file inside that folder with file name abc.jpg
i think your problem of line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); is only having folder path at the end. when you call FileUpload1.SaveAs you need to have full file path.
Update
You get the error
System.IO.DirectoryNotFoundException: Could not find a part of the
path
because you don't have directory with the name of file name. I'm not where exactly you want to put the file. if you going to put the file in new directory, you need to create that directory first.
var folderpath = Server.MapPath(string.Format("~/{0}", Path.GetFileNameWithoutExtension(FileUpload1.FileName)));
System.IO.Directory.CreateDirectory(folderpath);
FileUpload1.SaveAs(Path.Combine(folderpath, FileUpload1.FileName));

Categories