file upload control problem - asp.net

i am using file upload control in server side when iam trying to get the file it is showing no file present
<asp:FileUpload ID="upldDocument" runat="server" />
string fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
if (upldDocument.HasFile)
{
}
i am getting a empty string as file extension and upldDocument.HasFile is returning false even after selecting a file.
what could be the reason??

Based on the posted code, I can only offer a best guess. There's not enough code posted to be sure what the problem is, but here's my best guess:
If you're not already, you need to check the HasFile property.
See here for a full example:
Edit - added
Using HasFile AFTER the bad code won't help. You need to put the code to get the extention inside an if statement so that it only attempts to read the extension if there IS a file.
string fileExtension = "";
if (upldDocument.HasFile)
{
fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
}
else
{
//No file selected by user, which is why you can't get the extension.
// handle this eventuality here even if it means just returning from the function and not doing anything.
}

How are you checking the values? (in what event)
Did you set the enctype attribute of the form to "multipart/form-data" ?

Related

mvc 5 read and display text file content

I am trying to read a text file and display it on plage. This is what I did. But I am getting error
The process cannot access the file
'D:\wwwroot\TestProject\Logs\TestLog.log' because it is being used by
another process.
Controller Code
Array LogFileData = null;
var logFileNameWithPath = Server.MapPath("D:\wwwroot\TestProject\Logs\TestLog.log");
if (System.IO.File.Exists(logFileNameWithPath))
{
LogFileData = System.IO.File.ReadAllLines(logFileNameWithPath);
}
ViewBag.logFileContent = LogFileData;
View Code
#if (ViewBag.logFileContent != null)
{
foreach (string dataLine in ViewBag.logFileContent)
{
#dataLine
<br />
}
}
The log file is created and used by a service. My code works when I stop service. But I am not trying to write to file exclusively at the same time service is writing to it. Infact I am trying to read at a time when service is not writing to it. Any advice on how can I fix this? THanks.
Generally, you need to specify the "access mode" when you try to read the file. Please take a look here. Try to open the file into a FileStream with appropriate access.
I will post some code when I can.

Edit xml File and save it from c#

I have an xml file which contain images url . i am verifying the url whether url is responsive or not. If url is not responsive then i am removing that url from xml. and saving all changes . but i am getting error like
'The process cannot access the file 'E:\1.xml' because it is being used by another process'
xmlTR = new XmlTextReader(#"E:\1.xml");
PrimaryXmlDoc.Load(xmlTR);
foreach (XmlNode node in PrimaryXmlDoc.SelectNodes("/fp-hotel/Images/Url"))
{
if (CheckUrlExists(node.InnerText))
{
}
else
{
XmlElement _xmlElement = PrimaryXmlDoc.DocumentElement;
node.ParentNode.RemoveChild(node);
}
}
PrimaryXmlDoc.Save(#"E:\1.xml");
I assume that you have to Close XmlTextReader before using it second time. If you don't do that, the previous instance will keep your file open and you won't be able to open it again.
EDIT: And that's what happens here is probably that you want to save file before closing it.
Add line:
xmlTR.Close();
before
PrimaryXmlDoc.Save(#"E:\1.xml");

How to get the Filename in code behind on selecting a file, before uploading it to the server using aspx and CS?

I want to retrieve the file name and perform some validation on that filename. so before uploading i have to get the filename of the file selected for uploading.
Actually what i wanted is to get the filename and retrieve some fields from database based on which file is chosen , and send the data retrieved from database on the client side in some textfield. So for that before on click of upload i need to call a method in code behind which will validate all these things. I tried using AjaxControlToolkit, its not working.
Use GetFileName() method. Below example from MSDN link.
string fileName = #"C:\mydir\myfile.ext";
string path = #"C:\mydir\";
string result;
result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
// This code produces output similar to the following:
//
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext'
// GetFileName('C:\mydir\') returns ''
If you want to validate the filename on the client prior to sending it to the server you will not be able to do so with C#, you could quite easiy write a validation function in Javascript however.
You could perform server side validation of the file, but that would mean after uploading it. You could then make sure the file fulfills all your validation criterias and if it for some reason fails validation you could return the error message to the user. But that would mean a full postback of the page.
See below code example to get the file name :
var filePath = "C:\\SpiderCode\\MyFile.txt";
var fileName = System.IO.Path.GetFileName(filePath);
Client Side Code
<asp:FileUpload runat="server" ID="FileUpload" Width="100px" />
In code behind, check if user select any file, then it will simply gives you the file name in the fileName variable.
if (FileUpload.HasFile)
{
string fileName = FileUpload.FileName;
}

jQuery UI autocomplete is not displaying results fetched via AJAX

I am trying to use the jQuery UI autocomplete feature in my web application. What I have set up is a page called SearchPreload.aspx. This page checks for a value (term) to come in along with another parameter. The page validates the values that are incoming, and then it pulls some data from the database and prints out a javascript array (ex: ["item1","item2"]) on the page. Code:
protected void Page_Load(object sender, EventArgs e)
{
string curVal;
string type ="";
if (Request.QueryString["term"] != null)
{
curVal = Request.QueryString["term"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
}
public string PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
sb.Append("[\"");
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\",\"");
}
}
sb.Append("\"];");
Response.Write(sb.ToString());
return sb.ToString();
}
}
The db part is working fine and printing out the correct data on the screen of the page if I navigate to it via browser.
The jQuery ui autocomplete is written as follows:
$(".searchBox").autocomplete({
source: "SearchPreload.aspx?Type=rbChoice",
minLength: 1
});
Now if my understanding is correct, every time I type in the search box, it should act as a keypress and fire my source to limit the data correct? When I through a debug statement in SearchPreload.aspx code behind, it appears that the page is not being hit at all.
If I wrap the autocomplete function in a .keypress function, then I get into the search preload page but still I do not get any results. I just want to show the results under the search box just like the default functionality example on the jQuery website. What am I doing wrong?
autocomplete will NOT display suggestions if the JSON returned by the server is invalid. So copy the following URL (or the returned JSON data) and paste it on JSONLint. See if your JSON is valid.
http://yourwebsite.com/path/to/Searchpreload.aspx?Type=rbChoice&term=Something
PS: I do not see that you're calling the PreLoadStrings function. I hope this is normal.
A couple of things to check.
Make sure that the path to the page is correct. If you are at http://mysite.com/subfolder/PageWithAutoComplete.aspx, and your searchpreload.aspx page is in another directory such as http://mysite.com/anotherFolder/searchpreload.aspx the url that you are using as the source would be incorrect, it would need to be
source: "/anotherFolder/Searchpreload.aspx?Type=rbChoice"
One other thing that you could try is to make the method that you are calling a page method on the searchpreload.aspx page. Typically when working with javascript, I try to use page methods to handle ajax reqeusts and send back it's data. More on page methods can be found here: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
HTH.

Add filter to FileUpload Control

How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.

Resources