Upload my files into folder using asp.net - asp.net

I want to upload my files into folder like
FileUpload1.SaveAs(Server.MapPath("~/admin_file/") + FileUpload1.FileName);
here my folder name admin_file.
protected void BindGrid() {
string[] filePaths = Directory.GetFiles(Server.MapPath("~/admin_file/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/admin_file/") + FileUpload1.FileName);
BindGrid();
}
else
{
//Response.Write("Please select file to upload");
string message = "alert('Please select file to upload!')";
ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);
}
}
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = (sender as LinkButton).CommandArgument;
File.Delete(filePath);
string message = "alert('Deleted Successfully!')";
ScriptManager.RegisterClientScriptBlock((sender as Control), this.GetType(), "alert", message, true);
BindGrid();
}
This program execute successfully in local system. When I publish this program to GODADDY not support so anybody tell how to give this path
otherwise send mail pramadivi#gmail.com

Read this troubleshooting article and follow according to it.
its better practice to use Path.Combine when concatenating folder+file name
FileUpload1.SaveAs(System.IO.Path.Combine(pathToFolder, fileName));

Related

How to browse & display excel sheet in web browser using asp.net?

i want to browse the excel input file & display it on web browser & it must be editable on web browser,
i am using C# asp.net for coding. Any help would be gr8. Thnks in advance.
I think the options you have are HTML tables or Google Spreadsheets / Microsoft Excel Online.
For more info:
http://www.labnol.org/software/embed-tables-spreadsheet-data-in-websites/7435/
In the webform:
Code behind:
protected void UploadFile(object sender, EventArgs e)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
Fileddl.Items.Add(new ListItem(Path.GetFileName(filePath), Path.GetFileName(filePath)));
}
}
}
protected void OpenFile(object sender, EventArgs e)
{
string filePath = Fileddl.SelectedItem.Value;
Myframe.Visible = true;
Myframe.Attributes.Add("src", "https://view.officeapps.live.com/op/embed.aspx?src=https://www.yoursite.com/Uploads/" + Path.GetFileName(filePath));
}
protected void DownloadFile(object sender, EventArgs e)
{
string filePath = Fileddl.SelectedItem.Value;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=https://www.yoursite.com/Uploads/" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
protected void DeleteFile(object sender, EventArgs e)
{
string filePath = Fileddl.SelectedItem.Value;
File.Delete(filePath);
Response.Redirect(Request.Url.AbsoluteUri);
}

Set value of TextBox after function execution asp.net

I try to make a site with a asp.net web application, but I can't continue because, I can not set the value of TextBox to "finish" after the execution of a function file download.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "start";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=print_ordre.pdf");
Response.TransmitFile(Server.MapPath("~/print_ordre.pdf"));
//Response.End();
TextBox1.Text = "finish";
}
I await your help ...

Object reference not set to an instance of an object

I am getting an error with an aspx Upload Control & Drop Down List on a single aspx page.
Here is the error...
Object reference not set to an instance of an object.
Here is my code for the on_submit...
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = Server.MapPath("~/files/");
//string uploadDirectory = "//DOCSD9F1/TECHDOCS/";
string uploadFolder = DropDownList1.SelectedItem.Text;
string fileName = e.UploadedFile.FileName;
string path = (uploadDirectory + uploadFolder + fileName);
e.UploadedFile.SaveAs(path);
e.CallbackData = fileName;
}
}`
here is my code for creating the drop down list...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files");
DropDownList1.DataSource = di.GetDirectories();
DropDownList1.DataBind();
foreach (DirectoryInfo i in di.GetDirectories())
{
DropDownList1.DataTextField = i.FullName;
DropDownList1.DataValueField = i.FullName;
}
}
}`
You might want to try this:
if(!Page.IsPostBack){
DirectoryInfo di = new DirectoryInfo("D:/SMGUpload/SMGUpload/files");
DirectoryInfo[] diArr = di.GetDirectories();
DropDownList1.DataSource = diArr;
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "Name";
DropDownList1.DataBind();
}
And get the selected value like:
string uploadFolder = DropDownList1.SelectedValue;
FYI: Make sure there are proper slashes(/) in the path you are creating while uploading the file.

return XML file to user

I am creating a XML file which I want to return to the user, when the user goes to a specified location. I have thought of something like:
return new FileStream("questions.xml",FileMode.Open);
Is this the proper code, or how would you return a file?
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
var file = Server.MapPath("~/questions.xml");
Response.WriteFile(file);
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=questions.xml");
}

How to make XMLTextWriter and XMLWriterSettings work together

I have this code for the settings:
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
settings.OmitXmlDeclaration = True
settings.NewLineOnAttributes = True
Then I have this code for the writer:
Dim xml As New XmlTextWriter(Server.MapPath("output.xml"), enc)
Please can you tell me how I make the settings apply to the writer?
Thanks a lot,
Phil.
EDIT: Code sample
Sub writexml_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Try
'Vars
Dim securityid As String = Input_securityid.Text
Dim enc As Encoding
Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
settings.OmitXmlDeclaration = True
settings.NewLineOnAttributes = True
settings.Encoding = enc
'Declare the writer and set file name / settings
Dim xml As XmlWriter = XmlWriter.Create(Server.MapPath("output.xml"), settings)
'start document
xml.WriteStartDocument()
xml.WriteComment("")
'start envelope
xml.WriteStartElement("soap", "Envelope", "http://schemas.xmlsoap.org/soap/envelope/")
'start body
xml.WriteStartElement("soap", "Body", Nothing)
xml.WriteAttributeString("xmlns", "ns1", Nothing, "http://its/foo.wsdl")
'start biographical capture
xml.WriteStartElement("ns1:biographicalcaptureElement")
'start securityid
xml.WriteStartElement("ns1:securityid")
xml.WriteValue(securityid)
'end securityid
xml.WriteEndElement()
'start requestdata
xml.WriteStartElement("ns1:requestdata")
'end requestdata
xml.WriteEndElement()
'end biographical capture
xml.WriteEndElement()
'end body
xml.WriteEndElement()
'end envelope
xml.WriteEndElement()
'end document
xml.WriteEndDocument()
'clean up
xml.Flush()
xml.Close()
Catch ex As Exception
errorlbl.Text = ex.ToString
Finally
errorlbl.Text = ("Created file ok")
End Try
End Sub
It does work fine if I use;
Dim xml As New XmlTextWriter(Server.MapPath("output.xml"), enc)
the xml is produced but settings are not applied.
This won't get you an XmlTextWriter, but to be honest I've always used XmlWriter when writing to a file anyway (XmlWriter is the base class of XmlTextWriter.)
You can use XmlWriter.Create(Server.MapPath("output.xml"), settings) which will give you an XmlWriter instead of an XmlTextWriter. Your encoding will then need to be set in your settings instance (settings.Encoding = enc.)
EDIT:
The sample code provided for me produces:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body xmlns:ns1="http://its/foo.wsdl" />
</soap:Envelope>
EDIT 2:
Your namespace is causing a problem because it's trying to put the element name as ns1:securityid when it should be the element name is securityid and the namespace ns1. You'll need to separate these like you've done in the WriteAttributeString call, like so:
instead of: xml.WriteStartElement("ns1:biographicalcaptureElement")
use: xml.WriteStartElement("biographicalcaptureElement", "ns1")
With these changes in place I now get:
<!---->
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body xmlns:ns1="http://its/foo.wsdl">
<biographicalcaptureElement xmlns="ns1">
<securityid>TEST123</securityid>
<requestdata />
</biographicalcaptureElement>
</soap:Body>
</soap:Envelope>
public partial class XMLWriter : System.Web.UI.Page
{
static string strFileName=#"E:\vijay112.xml";
static XmlTextWriter write = null;
public static int i = 0;
////// static string ProcessName=Process.GetCurrentProcess().ProcessName;
//////static Process[] processes = Process.GetProcessesByName(ProcessName);
////// if ( // {
////// // Application.ExitThread();
////// // }
public XMLWriter()
{
}
~XMLWriter()
{
//write.Close(); ;
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
write = new XmlTextWriter(strFileName, null);
div_div.InnerText = i.ToString();
}
catch (Exception ex)
{
}
}
public static string XMLWrite()
{
try
{
if (i == 0)
return "success";
else
{
return "please end the"+i+"more child";
}
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
try
{
}
catch ( Exception ex){}
}
}
public static void SetRootElement(string strRootElement)
{
write.WriteStartElement(strRootElement);
}
//public static void SetAttributeString(string strRootElement)
//{
// write.WriteString();
//}
public static void SetChildElement(string strChildElement)
{
write.WriteStartElement(strChildElement);
}
public static void SetAttribute(string strAttribute, string strValue)
{
write.WriteAttributeString(strAttribute, strValue);
}
public static void EndChildElement()
{
write.WriteEndElement();
}
public static void EndRootElement()
{
write.WriteFullEndElement();
}
protected void Bt_root_Click(object sender, EventArgs e)
{
SetRootElement(TB_key.Text);
}
protected void bt_child_Click(object sender, EventArgs e)
{
++i;
SetChildElement(TB_key.Text);
}
protected void BT_attribute_Click(object sender, EventArgs e)
{
SetAttribute(TB_key.Text, TB_value.Text);
}
protected void bt_endChild_Click(object sender, EventArgs e)
{
--i;
EndChildElement();
}
protected void bt_endroot_Click(object sender, EventArgs e)
{
EndRootElement();
}
protected void bt_xml_Click(object sender, EventArgs e)
{
write.Close();
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(#"E:\vijay\SourceCodeBackEnd\PrimeroWebService\Images\vijay112.xml");
// write.Flush();
Txml.Text= xmldoc.InnerXml;
}
protected void Txml_TextChanged(object sender, EventArgs e)
{
}
protected void bt_close_Click(object sender, EventArgs e)
{
}
}

Resources