uploading file and viewing the content of the file

Hi Experts,
  I am trying to write the program in C# to upload the file and also to view the content of the file. I would appreciate your help with the code. Thanks,

Sudhir
sudAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

C_Sharp_ProgrammerCommented:
What kind of file are you trying to open?
sudAuthor Commented:
Hi C_Sharp_Programmer,

Its a ASCII text file.
Thanks,

Sudhir
Bob LearnedCommented:
Uploading data:

using System.Net;

public void UploadData(string address, byte[] data)
{

   WebClient client = new WebClient();

   client.UploadData(address, data);

}

Bob

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

sudAuthor Commented:
Hi Bob,
  thats all you need to code for uploading the file.Thanks,

Sudhr
Bob LearnedCommented:
That may not be all the code, it just depends on what web site, and the connection method.  That is the simplest form.  It can be much more complicated.

Bob
sudAuthor Commented:
Thanks Bob,
   What if i need to view the content of the text file that i have uploaded? Thanks,

Sudhir
Bob LearnedCommented:
using System.IO;

public string ReadFile(string path)
{
 
   StreamReader sr = new StreamReader(path);

   string fileText = sr.ReadToEnd();

   return fileText;

}

Bob
sudAuthor Commented:
Hi Bob,
 Here is my C# code it gives me error :

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {   public void UploadData(string address, byte[] data)
{

   WebClient client = new WebClient();

   client.UploadData(C:\, byte[] data);

}

    }

Any suggestion ?

thanks,

sudhir
Bob LearnedCommented:
What are you trying to accomplish here?  Do you want to upload any particular types of files?

Bob
sudAuthor Commented:
I want to upload text file. thanks,

Sudhir
Bob LearnedCommented:
If you look at WebClient.UploadData, you will notice something interesting:

   "Uploads a data buffer to a resource with the specified URI."

WebClient.UploadData Method:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemnetwebclientclassuploaddatatopic.asp

Look at the example code, and see if it fits your requirement.

Bob
sudAuthor Commented:
Hi Bob,
  Is it possibe for you to give me a simple program to upload a text file to my C:\\ . Thanks,

Sudhir
Bob LearnedCommented:
I don't understand.

Are you talking upload from or download to?  Upload from another computer to a site, and put it on the hard drive?  Download a file from a web site, and store on your C:\ drive?

Bob
DivinityCommented:
I don't want to butt in, but you placed the UploadData method in the Page_Load event method. That's probably what is giving you the error.
sudAuthor Commented:
Hi Bob,
    Sorry for the confusion.   Upload from any computer to site and put it on a C:\\ drive of the server.

Thanks,

Sudhir
sudAuthor Commented:
Hi Experts,
   I am posting my c# script files that i am using to upload but i am not able to do so. I would appreciate if someone can help me with debugging.


File: upload.aspx

<%@ Page language="c#" Codebehind="Upload.aspx.cs" AutoEventWireup="false" Inherits="FileUpload.UploadForm" Trace="true" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" enctype="multipart/form-data" method="post" runat="server">
<H2 align="center"><FONT face="Arial Black, Arial">Upload File to Web Server</FONT></H2>
<P>
<INPUT type="file" runat="server" id="File1">
</P>
<P>
<asp:Button id="btnUpload" runat="server" Text="Upload File"></asp:Button></P>
</form>
</body>
</HTML>

FILE: upload.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace FileUpload
{
/// <summary>
/// Summary description for WebForm1.
/// </summary>
public class UploadForm : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnUpload;
protected System.Web.UI.HtmlControls.HtmlInputFile File1;

private void Page_Load(object sender, System.EventArgs e)
{
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion

private void btnUpload_Click(object sender, System.EventArgs e)
{
HttpPostedFile file = File1.PostedFile;

if (file.FileName != "")
{
Debug.WriteLine(file.ContentLength.ToString());
string filename = GetFileName(file);
if (file.ContentType.IndexOf("excel") >= 0)
file.SaveAs(Server.MapPath(@"\Upload\Excel\" + filename));
else if (file.ContentType.IndexOf("word") >= 0)
file.SaveAs(Server.MapPath(@"\Upload\Word\" + filename));
else
file.SaveAs(Server.MapPath(@"\Upload\Other\" + filename));
}
}

private string GetFileName(HttpPostedFile file)
{
int i=0, j=0;
string filename;

filename = file.FileName;
do
{
i = filename.IndexOf(@"\",j+1);
if (i>=0) j=i;
} while (i>=0);
filename = filename.Substring(j+1,filename.Length-j-1);

return filename;
}
}
}



Thanks,

Sudhir
sudAuthor Commented:
Hi Experts,
  Here is the code that works,may be it may be helpfull to other users.Thanks.


 
namespace FileUpload
{    
       public partial class WebForm1 : System.Web.UI.Page
       {
               string sFileDir= "C:\\";
              long lMaxFileSize = 4096;
     
              private void Page_Load(object sender, System.EventArgs e)
              {
              }
 
              private void DeleteFile (string strFileName)
              {//Delete file from the server
                     if (strFileName.Trim().Length > 0)
                     {
                           FileInfo fi = new FileInfo(strFileName);
                           if (fi.Exists)//if file exists delete it
                           {    
                                  fi.Delete();
                           }
                     }
              }
 
              #region Web Form Designer generated code
              override protected void OnInit(EventArgs e)
              {
                     //
                     // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                     //
                     InitializeComponent();
                     base.OnInit(e);
              }
             
              /// <summary>
              /// Required method for Designer support - do not modify
              /// the contents of this method with the code editor.
              /// </summary>
              private void InitializeComponent()
              {  
                     this.cmdUpload.Click += new System.EventHandler(this.cmdUpload_Click);
                     this.Load += new System.EventHandler(this.Page_Load);
 
 
              }
              #endregion
 
 
              private void cmdUpload_Click(object sender, System.EventArgs e)
              {
                   
                     if (( File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
                     {
                           //determine file name
                           string sFileName = System.IO.Path.GetFileName(File1.PostedFile.FileName);
                           try
                           {
                                  if (File1.PostedFile.ContentLength <= lMaxFileSize)
                                  {
                                         //Save File on disk
                                         File1.PostedFile.SaveAs(sFileDir + sFileName);
                                         lblMessage.Visible=true;
                                         lblMessage.Text="File: " + sFileDir + sFileName + " Uploaded Successfully";
                                  }
                                  else //reject file
                                  {
                                         lblMessage.Visible=true;
                                         lblMessage.Text="File Size if Over the Limit of " + lMaxFileSize ;
                                  }
                           }
                           catch (Exception exp)//in case of an error
                           {

                               lblMessage.Visible = true;

                               lblMessage.Text = exp.Message;

                               DeleteFile(sFileDir + sFileName);

                           }


                         
                     }
              }
       }
}
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.