상세 컨텐츠

본문 제목

C# asp.net 파일 업로드, 삭제 생성, 수정 관련

프로그래밍 관련/웹

by AlrepondTech 2011. 4. 5. 15:39

본문

반응형

 

 

 

 

=================================

=================================

=================================

 

 

 

 

File Upload control in C# as a friendly web user control. Easy upload, delete, and view options

 

C# asp.net 파일 컨트롤 - 업로드, 삭제 생성, 수정

 

자료가 너무 좋아서 반햇심. 쫍쫍

 

The Source Code:

using System;

using System.Web;

using System.Web.UI.WebControls;

using System.ComponentModel;

using System.IO;

 

public partial class Controls_FileUpload : System.Web.UI.UserControl

{

private string SaveToPath = "";

private string VirtualPath = "";

 

#region File Upload Control Properties

/// <summary>

/// Save Location of File. Example "C:\TEMP\"

/// </summary>

[Browsable(true), Category("Properties"), Description("Save Location of File")]

public string File_Save_Path

{

get

{

return SaveToPath;

}

set

{

SaveToPath = value;

}

}

 

/// <summary>

/// Virtual Path of document. Example: "http://servername/filedirpath/"

/// </summary>

[Browsable(true), Category("Properties"), Description("Virtual Path of document")]

public string Virtual_Path

{

get

{

return VirtualPath;

}

set

{

VirtualPath = value;

}

 

}

 

#endregion

 

protected void Page_Load(object sender, EventArgs e)

{

this.lblError.Text = "";

 

if (!Page.IsPostBack)

{

if (this.VirtualPath.Length == 0)

{

this.lblError.Text = "Virtual Path Property has not been set.";

this.Panel_Control.Enabled = false;

return;

}

else if (this.SaveToPath.Length == 0)

{

this.lblError.Text = "Save To Path Property has not been set.";

this.Panel_Control.Enabled = false;

return;

}

else

{

if (ValidatePath() == true)

{

if (ShowAllFiles() == false)

{

//An error occured.

this.Panel_Control.Enabled = false;

return;

}

}

else

{

this.Panel_Control.Enabled = false;

return;

}

}

}

}

 

/// <summary>

/// Validates if the Path exists. If it doesn't we try to create it.

/// </summary>

private bool ValidatePath()

{

try

{

if (System.IO.Directory.Exists(SaveToPath) == false)

{

System.IO.Directory.CreateDirectory(SaveToPath);

return true;

}

else

{

return true;

}

}

catch (Exception ex)

{

lblError.Text = "Error: " + ex.Message.ToString();

return false;

}

}

 

/// <summary>

/// Shows all the files in this directory.

/// </summary>

private bool ShowAllFiles()

{

try

{

//Clear the list box

lstDocs.Items.Clear();

 

//Get all the directory files

string[] subfiles = Directory.GetFiles(SaveToPath);

foreach (string file_obj in subfiles)

{

string doc_name = System.IO.Path.GetFileName(file_obj);

 

//text is document name

//value is full path to document

ListItem tempItem = new ListItem(doc_name, file_obj);

 

//add to list box

lstDocs.Items.Add(tempItem);

}

 

return true;

}

catch (Exception ex)

{

this.lblError.Text = "Error: " + ex.Message.ToString();

return false;

}

}

 

/// <summary>

/// Upload File

/// </summary>

protected void btnUpload_Click(object sender, EventArgs e)

{

try

{

if (filePSE.PostedFile.FileName == "" || filePSE.PostedFile.ContentLength == 0)

{

return;

}

 

string path = filePSE.PostedFile.FileName;

string doc_name = System.IO.Path.GetFileName(path);

string err = "";

 

bool isSafeFile = CheckExtensions(doc_name);

if (isSafeFile == false)

{

return;

}

 

if (System.IO.File.Exists(SaveToPath + doc_name))

{

this.lblError.Text = "A file with this name already exists.";

return;

}

 

filePSE.PostedFile.SaveAs(SaveToPath + doc_name);

 

//Create list item with text as document name

//and value as full path

ListItem item = new ListItem(doc_name, SaveToPath + doc_name);

 

//add to list box

lstDocs.Items.Add(item);

 

this.lblError.Text = "File uploaded successfully.";

 

}

catch (Exception ex)

{

Response.Write("Error Uploading File: " + ex.Message.ToString());

Response.End();

}

}

 

/// <summary>

/// Delete File

/// </summary>

protected void btnDelete_Click(object sender, EventArgs e)

{

try

{

if (this.lstDocs.Items.Count == 0)

{

lblError.Text = "No items to delete";

return;

}

else if (this.lstDocs.SelectedIndex == -1)

{

lblError.Text = "Please select an item to delete";

return;

}

else

{

//get temp of selected item

string path = lstDocs.SelectedItem.Value;

 

//delete the file

System.IO.File.Delete(path);

 

//Remove list item

lstDocs.Items.Remove(lstDocs.SelectedItem);

 

this.lblError.Text = "File deleted successfully.";

}

}

catch(Exception ex)

{

Response.Write("Error Deleting File: " + ex.Message.ToString());

Response.End();

}

}

 

/// <summary>

/// Check if it part of allowed extensions

/// </summary>

private bool CheckExtensions(string filename)

{

try

{

/*

if ( (filename.ToLower().LastIndexOf(".doc") == -1) &&

(filename.ToLower().LastIndexOf(".pdf") == -1) &&

(filename.ToLower().LastIndexOf(".ppt") == -1) &&

(filename.ToLower().LastIndexOf(".txt") == -1) &&

(filename.ToLower().LastIndexOf(".xls") == -1) )

*/

if ((filename.ToLower().LastIndexOf(".exe") != -1))

{

this.lblError.Text = "This type of file cannot be uploaded.";

return false;

}

else

{

return true;

}

}

catch (Exception ex)

{

Response.Write("Error: " + ex.Message.ToString());

Response.End();

//The line below will never execute.

return false;

}

}

 

/// <summary>

/// Checks if we have any items, and if so generates javascript for double click.

/// </summary>

protected override void OnPreRender(EventArgs e)

{

if (lstDocs.Items.Count > 0)

{

/*

if you want to alert the value for error checking, use the following:

this.lstDocs.Attributes["ondblclick"] = "alert(this.options[this.selectedIndex].text); window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";

instead of

*/

this.lstDocs.Attributes["ondblclick"] = "window.open('" + Virtual_Path + "' + this.options[this.selectedIndex].text );";

}

else

{

this.lstDocs.Attributes.Remove("ondblclick");

}

base.OnPreRender(e);

}

}


=================================

=================================

=================================

 

 

 

반응형


관련글 더보기

댓글 영역