Upload and Delete file by using File Upload Control asp.net - asp.net

I am developing a complaint form. In this this form, I must make a function that uploads a file and then delete the file that was uploaded. I can upload a file to the server, but I can't take a link of the file I upload to the server in order to delete it. Please help me. Here is my code:
public string FilePath;
protected void btAdd_Click(object sender, EventArgs e)
{
if (AttachFile.HasFile)
{
try
{
string[] sizes = {"B", "KB", "MB", "GB"};
double sizeinbytes = AttachFile.FileBytes.Length;
string filename = Path.GetFileNameWithoutExtension(AttachFile.FileName);
string fileextension = Path.GetExtension(AttachFile.FileName);
int order = 0;
while (sizeinbytes >= 1024 && order + 1 < sizes.Length)
{
order++;
sizeinbytes = sizeinbytes/1024;
}
string result = String.Format("{0:0.##} {1}", sizeinbytes, sizes[order]);
string encryptionFileName = EncrytionString(10);
FilePath = "Path" + encryptionFileName.Trim() + AttachFile.FileName.Trim();
AttachFile.SaveAs(FilePath);
}
catch (Exception ex)
{
lbMessage.Visible = true;
lbMessage.Text = ex.Message;
}
}
}
protected void btDelete_Click(object sender, EventArgs e)
{
try
{
File file = new FileInfo(FilePath);
if (file.Exists)
{
File.Delete(FilePath);
}
}
catch (FileNotFoundException fe)
{
lbMessage.Text = fe.Message;
}
catch (Exception ex)
{
lbMessage.Text = ex.Message;
}
}

Each request in asp.net creates a new object of your Page.
If you set variables during one request, they will not be available on the next request.
Your delete logic seems to depend upon FilePath being set during upload. If you want the page to remember that, keep it in the ViewState. The ViewState is maintained across requests to the same page and that would allow you to use the variable FilePath during delete.
This can be easily achieved by making FilePath a property and getting it from the ViewState.
public string FilePath
{
get
{
return (string) ViewState["FilePath"];
}
set
{
ViewState["FilePath"] = value;
}
}

YOU SHOULD DO IT IN THIS WAY.
if (imgUpload.HasFile)
{
String strFileName = imgUpload.PostedFile.FileName;
imgUpload.PostedFile.SaveAs(Server.MapPath("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
SqlCommand cmd01 = new SqlCommand("insert into img (FeaturedImg) Values (#img)", cn01);
cmd01.Parameters.AddWithValue("#img", ("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
}
With this code you can upload file in a particular location in your sites root directory.
and the path will be stored in database as string.
so you can access the file just by using the path stored in database.
If you cant understand anything. or wanna know more u can contact me or ask me here in comments.

Related

How to store image in solution using ASP.NET?

I have an upload image function that uploads images to the server but I am only able to add images into the server until the session ends. Once the session ends , I noticed that the images uploaded are not stored into my local solution and after some research I found out that we could make uploaded files be stored into our solution even when the session ends but I am unsure of how to implement it. I am very new to this and would appreciate all help given.
For now this is the code I have that allows me to upload my image:
protected void btnConfirm_Click(object sender, EventArgs e)
{
string uploadedPhoto = "";
if (uploadImage.HasFile)
{
string savePath;
//Find the filename extension of the file to be uploaded.
string fileExt = Path.GetExtension(uploadImage.FileName);
//rename the uploaded file with name
uploadedPhoto = txtName.Text + fileExt;
savePath = MapPath("~/Images/profile pictures/" + uploadedPhoto);
try
{
uploadImage.SaveAs(savePath);
lblMsg.Text = "Image uploaded!";
imgprw.ImageUrl = "~/Images/profile pictures/" + uploadedPhoto;
}
catch (IOException)
{
lblMsg.Text = "Image upload failed!";
}
catch (Exception ex)
{
lblMsg.Text = ex.Message;
}
}
}
I see your code is right because I used same way to upload and store image into folder like you.
string path = Server.MapPath("~/Photos/" + f.FileName);
f.SaveAs(path);
May I see your full code ?

Browse and upload file

I have a ASP.NET (.NET Framework 3.5) Application. Now, I have to place a Button on a aspx-Page with the fallowing functionality on click:
Ask the user for a file with Extension xls (OpenFileDialog)
Upload the selected file to a specific folder on the WebServer
How can I do this?
Thanks for your help.
Here is the code that can be used for file upload after checking certain file types.
protected void Upload_File() {
bool correctExtension = false;
if (FileUpload1.HasFile) {
string fileName = FileUpload1.PostedFile.FileName;
string fileExtension = Path.GetExtension(fileName).ToLower();
string[] extensionsAllowed = {".xls", ".docx", ".txt"};
for (int i = 0; i < extensionsAllowed.Length; i++) {
if (fileExtension == extensionsAllowed[i]) {
correctExtension = true;
}
}
if (correctExtension) {
try {
string fileSavePath = Server.MapPath("~/Files/");
FileUpload1.PostedFile.SaveAs(fileSavePath + fileName);
Label1.Text = "File successfully uploaded";
}
catch (Exception ex) {
Label1.Text = "Unable to upload file";
}
}
else {
Label1.Text = "File extension " + fileExtension + " is not allowed";
}
}
}
You should start with the ASP.NET FileUpload control. Here is a pretty good tutorial on how to complete this task.

Silverlight OOB WebBrowser Exception

I've got an oob app with a webbrowser on it.
The webbrowser source is databound with a URI defined by me. The URI has a path to a webpage from my server that displays a PDF file from its hardrive.
Note that all this is done on a local network.
URI example: uri = new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
Page code-behind:
protected void Page_Load(object sender, EventArgs e)
{
string myURL = Request.Url.ToString();
string[] ParamArray = Regex.Split(myURL, "pdf=");
string Params = ParamArray[ParamArray.Length - 1];
if (Params.Length > 0)
{
Filename = Regex.Replace(Params, #"//", #"\\"); ;
if (File.Exists(Filename))
{
Response.ContentType = "Application/pdf";
Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream.
Response.End();
}
else
this.Title = "PDF Not Found";
}
}
protected void Page_Load(object sender, EventArgs e) { string myURL = Request.Url.ToString(); string[] ParamArray = Regex.Split(myURL, "pdf="); //If the URL has parameters, then get them. If not, return a blank string string Params = ParamArray[ParamArray.Length - 1]; if (Params.Length > 0) { //to the called (src) web page Filename = Regex.Replace(Params, #"//", #"\\"); ; if (File.Exists(Filename)) { Response.ContentType = "Application/pdf"; Response.WriteFile(Filename); //Write the file directly to the HTTP content output stream. Response.End(); } else this.Title = "PDF Not Found"; } }
The first time I set the WebBrowser source everything it displays the PDF. But when I set the URI one second time the app throws an exception: Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100).
I've done a few tests and here are the results:
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
1º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
2º new Uri(#"http://www.google.com"); ->error
1º new Uri(#"http://www.google.com");
2º new Uri(#"http://www.microsoft.com");
2º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=somePDF.pdf");
3º new Uri(#"http://ServerName/ProjectName/PDFViewer.aspx?pdf=someOtherPDF.pdf"); ->error
I also forgot to say that when running the app from my browser (using a HTMLHost) the pages display just fine. Opening the pages using a browser will also work well.
It must be some problem with my aspx page. Any ideas?
Pedro
I've managed to resolve this by creating a new browser for each page. If you know of a more elegant solution please share.
I am not sure if I'm following the question/problem correctly but maybe loading the pages async and then assigning to webbrowser? Forgive me if I am off-base here.
public void ShowLink(string linkUrl)
{
if (App.Current.IsRunningOutOfBrowser)
{
var pageRequest = new WebClient();
pageRequest.DownloadStringCompleted += pageRequest_DownloadStringCompleted;
pageRequest.DownloadStringAsync(new Uri(linkUrl, UriKind.Absolute));
}
}
void pageRequest_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
webBrowserLink.NavigateToString(e.Result.ToString());
}

how to use FileSystemWatcher using asp.net(C#)

SENARIO: i have few folders on my FTP server, belongs to particular user. Suppose i have 10GB total space and i assign 1GB to each user i.e can accomodate 10 users having 1GB each.
now users can add/delete/edit any type of file to utilize the storage space. All i need to do is to restrict users not to exceed 1gb space for their file storage. For this i want to use FileSystemWatcher to notify me that a user had created/deleted/edited a file so that i can minimize the space from 1gb incase of creation of a file or add a space incase of deletion.
this is the piece of coding using FSW. when user gets loged-in with proper id and password, respective folder is opened (present at FTP server) where he can add/delete/edit any type of file and according to that i hav to monitor d space ulitilized by him.
but d problem is the event handlers (written in console). i dont understand what happens when this code is being runned... i dontknow how to use FSW class so that i can monitor d changes user is making in his folder.
please help ... THANX
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
public class _Default: System.Web.UI.Page {
public class ClsFileSystemWatcher {
public static void OnChanged(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnDeleted(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnCreated(object source, FileSystemEventArgs e) {
Console.WriteLine("File "+e.FullPath+" :"+e.ChangeType);
}
public static void OnRenamed(object source, RenamedEventArgs e) {
Console.WriteLine("File "+e.OldFullPath+" [Changed to] "+e.FullPath);
}
public static void OnError(object source, ErrorEventArgs e) {
Console.WriteLine("Error "+e);
}
public void FileWatcher(string InputDir) {
using (FileSystemWatcher fsw = new FileSystemWatcher()) {
fsw.Path = InputDir;
fsw.Filter = #"*";
fsw.IncludeSubdirectories = true;
fsw.NotifyFilter = NotifyFilters.FileName|NotifyFilters.Attributes|NotifyFilters.LastAccess|NotifyFilters.LastWrite|NotifyFilters.Security|NotifyFilters.Size|NotifyFilters.CreationTime|NotifyFilters.DirectoryName;
fsw.Changed += OnChanged;
fsw.Created += OnCreated;
fsw.Deleted += OnDeleted;
fsw.Renamed += OnRenamed;
fsw.Error += OnError;
fsw.EnableRaisingEvents = true;
//string strOldFile = InputDir + "OldFile.txt";
//string strNewFile = InputDir + "CreatedFile.txt";
//// Making changes in existing file
//using (FileStream stream = File.Open(strOldFile, FileMode.Append))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Appending new line in Old File");
// sw.Flush();
// sw.Close();
//}
//// Writing new file on FileSystem
//using (FileStream stream = File.Create(strNewFile))
//{
// StreamWriter sw = new StreamWriter(stream);
// sw.Write("Writing First line into the File");
// sw.Flush();
// sw.Close();
//}
//File.Delete(strOldFile);
//File.Delete(strNewFile);
// Minimum time given to event handler to track new events raised by the filesystem.
Thread.Sleep(1000);
}
}
}
private DAL conn;
private string connection;
private string id = string.Empty;
protected void Page_Load(object sender, EventArgs e) {
connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\project\\Desktop\\BE prj\\dbsan.mdb;Persist Security Info=False";
conn = new DAL(connection);
////*** Opening Respective Folder of a User ***////
DirectoryInfo directories = new DirectoryInfo(#"C:\\Inetpub\\ftproot\\san\\");
DirectoryInfo[] folderList = directories.GetDirectories();
if (Request.QueryString["id"] != null) {
id = Request.QueryString["id"];
}
string path = Path.Combine(#"C:\\Inetpub\\ftproot\\san\\", id);
int folder_count = folderList.Length;
for (int j = 0; j < folder_count; j++) {
if (Convert.ToString(folderList[j]) == id) {
Process p = new Process();
p.StartInfo.FileName = path;
p.Start();
}
}
ClsFileSystemWatcher FSysWatcher = new ClsFileSystemWatcher();
FSysWatcher.FileWatcher(path);
}
}
Each time you reload the page you create new FSW - in that case you won't get any events raised, because from the point of newly created FSW nothing was changes. Try to preserve your FileSystemWatcher object in the Session state.
So flow would look like:
User logs in – you create FSW and preserve it in Session
User reloads the page – get FSW from Session (do not create new one)
You should create a worker role (service) for this type of thing. I think it is not appropriate to have something like this inside of a page.

How to change fileupload name

im using following code to upload
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~upload/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
I want to change the upload file name...I have to assign file name for every uploaded file how?
This line pickes up the the name of the uploaded file:
string filename = Path.GetFileName(FileUploadControl.FileName);
This line tells the server what to save the file as:
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
Simply change the value of filename to something else before saving.
there is a way to change the name of the file that we downloaded to our "~Server/Userfolder"(as an example)..
i was really thinking on renaming file before the .SaveAs command, which is gonna be like:
if (Request.Files != null)
{
var getmyfile = Request.Files["some_photo"];
try
{
if (getmyfile.FileName != "" && getmyfile.FileName != null && getmyfile.ContentLength > 0)
{
///Create Useruploads path.
var path = Server.MapPath("~/Useruploads" + "\\");
///Get file info that we gonna upload to server..
FileInfo TheFile = new FileInfo(path + Path.GetFileName(getmyfile.FileName));
///Note: i used Path.GetFileName(getmyfile.FileName) code cause getmyfile.FileName gives full path of that file..
if (TheFile.Exists)
{
///Seperate file name and extention..
var fname = Path.GetFileNameWithoutExtension(TheFile.Name);
var ext = TheFile.Extension;
var path2 = path + fname;
///As long as we got file names, same as in server..
while(new FileInfo(path2+ext).Exists)
{
///Add "-img" to its name..
path2 = path2 + "-img";
}
FileInfo ccc = new FileInfo(path2 + ext);
string f_art = ccc.Name.Replace(" ", "");///Clean space.. (Optional)
getmyfile.SaveAs(f_art);
somedb.some_photo = Path.GetFileName(f_art); ///Its not fart its file art lol!
}
else ///if file is not exist in our server..
{
var path3 = (path + Path.GetFileName(getmyfile.FileName));
FileInfo ccc = new FileInfo(path3);
string f_art = ccc.Name.Replace(" ", "");
getmyfile.SaveAs(f_art);
some.some_photo = Path.GetFileName(f_art);
}
}
}
catch(FileNotFoundException ex)
{
form.Set("lblStatus",ex.Message);
}
catch (Exception ex)
{
form.Set("lblStatus", ex.Message);
}
db.somedbs.InsertOnSubmit(somedb);
db.SubmitChanges();
return RedirectToAction("Index");
}
(Optional) Also u can use :
var f_art = System.Text.RegularExpressions.Regex.Replace(Path.GetFileNameWithoutExtension(TheFile.Name), "[^a-zA-Z]", "");
instead of using .Replace(" ",""); but at this it just cleans spaced areas and if u use the code up there its gonna clean everything except A to Z , a to z characters which means no numbers will be applied to that name nor space or other characters which are not between A and Z..

Resources