Getting (The name 'file' does not exist in the current context) message - c#

UPDATE 1:
Here is the full code behind from the downloaded example, unedited:
using System;
using System.IO;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String UpPath;
UpPath = "C:\\UploadedUserFiles";
if (!Directory.Exists(UpPath))
{
Directory.CreateDirectory("C:\\UploadedUserFiles\\");
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
HttpFileCollection uploads = HttpContext.Current.Request.Files;
for (int i = 0; i < uploads.Count; i++)
{
HttpPostedFile upload = file;
if (upload.ContentLength == 0)
continue;
string c = System.IO.Path.GetFileName(upload.FileName); // We don't need the path, just the name.
try
{
upload.SaveAs("C:\\UploadedUserFiles\\" + c);
Span1.InnerHtml = "Upload(s) Successful.";
}
catch(Exception Exp)
{
Span1.InnerHtml = "Upload(s) FAILED.";
}
}
}
}
ORIGINAL QUESTION:
I've just downloaded a "file uploading" example from www.asp.net:
Link to tutorial: http://www.asp.net/web-forms/videos/how-do-i/how-do-i-multiple-file-uploads-in-aspnet-2
Link to download: http://download.microsoft.com/download/8/6/9/869ff08a-1e39-4bab-a303-f7dcedc52427/CS-ASP-MultiFileUpload-CS.zip
and copied the files to my webserver after extracting them.
When I navigate to http://server/uploader/Default.aspx
It creates the folder in the servers c drive successfully, but on the web browser I get the following error:
Server Error in '/' Application.
--------------------------------------------------------------------------------
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0103: The name 'file' does not exist in the current context
Source Error:
Line 29: for (int i = 0; i < uploads.Count; i++)
Line 30: {
Line 31: HttpPostedFile upload = file;
Line 32:
Line 33: if (upload.ContentLength == 0)
Source File: c:\Inetpub\wwwroot\uploader\Default.aspx.cs Line: 31
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3623; ASP.NET Version:2.0.50727.3618
Anyone know why this is happening?

You are addressing an undeclared local variable file, you should be retrieving the HttpPostedFile from the uploads "Items" collection using the Item index;
HttpPostedFile upload = uploads[i];

It seems a bug on the sample code. Try replacing this
HttpPostedFile upload = file
by
HttpPostedFile upload = uploads[i]

Along with "Default.aspx" and "Default.aspx.cs", you need "Default.aspx.Designer.cs" File.
As all the controls are defined with its style in "Designer" file.

Related

C# How to upload any file to a fileuploader?

I need upload my file to "https://file.io" and i tried this:
`private void buttonInput_Click(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
var resStr = client.UploadFile("https://file.io", #"C:\data\test.txt");
var jObjResult = JObject.Parse(Encoding.UTF8.GetString(resStr));
var linkToFile = jObjResult["link"];
}
}`
It does upload target txt file to url.
But im taking that error:
Severity Code Description Project File Line Hide Status
Error CS01 'JObject' scope valid03
How to Fix it?
Btw im using them:
using System;
using System.Net;
using System.Text;
using System.Collections.Generic;

Can't get Request.QueryString or similar methods to work

To my shame, because I can barely C#, I cannot manage to read the parameters from the URL.
I run a C# cgi executable on my IIS 7 as an application. The url that calls the executable is as below:
https://server/cgi/showEmail/showEmail.exe?email=john#gmail.com
The code starts as below:
using System;
using System.Web; // <---- isn't this for Request.QueryString ?
using System.Web.UI;
using System.Collections;
using System.Collections.Specialized;
using System.Data.SqlClient;
class showEmail
{
static void Main(string[] args)
{
Console.WriteLine("\r\n\r\n");
Console.WriteLine("<h1>Test</h1>");
try
{
Now, if I use the code below, the program compiles, but gives this a null exception when executed in the browser:
string email = HttpContext.Current.Request.QueryString["email"];
System.NullReferenceException: Object reference not set to an instance of an object. at showEmail.Main(String[] args)
and if I use this code below, the fun stops already at the compiler, who gives a "current context" exception:
string email = Request.QueryString["email"];
error CS0103: The name 'Request' does not exist in the current context
...
Am I missing something elementary that is required for the executable to see the url parameters?
Edit: I have looked through sof and many other places, but so far have not been able to connect the dots on this issue.
HttpContext.Current.Request is not available in console appliaction.
Use args parameter to receive query string parameter, like I am doing below.
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("parameter[{0}] is [{1}]", i, args[i]);
}
You might need to use below code to extract parameters from url received in args.
var url=args[0];
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
This is how I got it to work finally, please keep in mind this is not professionally validated code, more of try and try and try...
using System;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string email = Request.QueryString["email"] ?? "null";
if (email != "null") {

Can any one tell me how to upload an image from asp.net to godaddy server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace GodaddyImages
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~\\Images\\"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "~\\Images\\" + fileName));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
protected void Upload(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~\\Images\\") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}
Can any one tell me how to upload an image from asp.net to godaddy server.
I can upload images to local folders but found difficult in uploading into godaddy server
Typically in local system you will be having permissions to writing files(Images in this case). But when you are using server( or shared hosting) typically for security purposes they will give you read-only access to the folder that you deploy. But you can go ahead and still change the permissions of it when you are admin for that domain which you have hosted.The code required for uploading from asp.net is as straight forward as :
fileUpload.SaveAs(Server.MapPath("~/Images/") + fileUpload.FileName);
But, still for it work you need to have appropriate write permission for that particular folder.
Hope, it helps.

Server unable to execute EWS autodiscover

On our testing server, EWS autodiscover does not work. To eliminate an ill-set IIS option from the list of causes, I C&P'ed together a WindowsForms Application (code below) and put it, together with the Microsoft.Exchange.Webservice.dll, into a folder on which I have write permission.
Unfortunately, neither xml nor text file are created. Instead, I get an Unhandled Exception error.
System.NullReferenceException
at System.Windows.Forms.TextBoxBase.AppendText(String text)
This does not happen on my development machine, which is in the same AD domain and on which the test app always returns that autodiscover was successful.
Question: How come no Trace output is generated?
So now, my app code:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
namespace ADDebugWin
{
public partial class Form1 : Form
{
public static string traceData;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010);
ews.TraceListener = new TraceListener();
// Optional flags to indicate the requests and responses to trace.
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
ews.TraceEnabled = true;
ews.UseDefaultCredentials = true;
try {
ews.AutodiscoverUrl("email#mydomain.com");
textBox1.AppendText("AutoDiscover erfolgreich.");
} catch (Exception ex) {
textBox1.AppendText(traceData);
textBox1.AppendText(ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}
TraceListener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ADDebugMvc.Controllers;
using Microsoft.Exchange.WebServices.Data;
using System.Xml;
namespace ADDebugMvc.Models
{
class TraceListener : ITraceListener
{
public void Trace(string traceType, string traceMessage)
{
CreateXMLTextFile(traceType, traceMessage.ToString());
HomeController.traceData += traceType + " " + traceMessage.ToString() + "\r\n";
}
private void CreateXMLTextFile(string fileName, string traceContent)
{
// Create a new XML file for the trace information.
try
{
// If the trace data is valid XML, create an XmlDocument object and save.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(traceContent);
xmlDoc.Save(fileName + ".xml");
}
catch
{
// If the trace data is not valid XML, save it as a text document.
System.IO.File.WriteAllText(fileName + ".txt", traceContent);
}
}
}
}
One should note that
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
is not returning any Traces during AutoDiscover.
(ews.TraceFlags = TraceFlags.All; does.)
So no string is appended to traceData, which is why traceData==null -> Exception when appending it to a TextBox.

fileupload control causing server error

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String fn = FileUpload1.FileName;
string fp = Server.MapPath("images");
if (fp.EndsWith("\\") == false)
{
fp = fp + "\\";
}
fp = fp + fn;
FileUpload1.PostedFile.SaveAs(fp);
}
}
on runnning this code, i receive the following error:
Server Error in '/WebSite11' Application
HTTP Error 400 - Bad Request.
Version Information:
ASP.NET Development Server 10.0.0.0
If the images folder is located at the root of your site then path should be this
string fp = Server.MapPath(~"/images");
and also try to run the site on a different brwose bcz few days ago i saw the same issue but when he rans the code on a different browse it works fine.
see the following post
HTTP Error 400 - Bad Request due to FileUpload control in vb.net

Categories