How to clear file upload text in server side (c#) - c#

I want to clear the file path from the file upload. The file upload is inside the update panel and I am using a AsyncFileUpload. How can I clear the file and change the background color of the fileupload
btnAudUpload_Click Method
string filename =FileUpload.FileName;
string Fullpath = Path.Combine(#"D:\Media", filename);
if (FileUpload.HasFile)
{
if (filename.ToLower().EndsWith("mp4"))
{
//Saving the file
}
else
{
//I want to clear the FileUpload content here
}
}

Clear the Attributes worked for me... but that will remove styles and other stuff
string filename =FileUpload.FileName;
string Fullpath = Path.Combine(#"D:\Media", filename);
if (FileUpload.HasFile)
{
if (filename.ToLower().EndsWith("mp4"))
{
//Saving the file
}
else
{
//I want to clear the FileUpload content here
FileUpload.Attributes.Clear();
}
}

I know this thread is almost a year old, but this still seems to be a prevalent issue. The easiest fix I've found is to set the file upload control to a new instance of it.
FileUpload1 = new FileUpload();

If you want to have interactivity without relouding the page you'll have to use JavaScript. That's why I would check the file extension on the client side instead of the server side. Example:
function checkFile() {
var input = document.getElementById('fileUpload').value.toLowerCase();
var extension = '.mp4';
if (!input.indexOf(extension, input.length - extension.length) != -1) {
alert('Invalid file extension. Only .mp4 is allowed.');
document.getElementById('fileUpload').value = '';
}
}
The only thing you'll have to add is changing the fileUpload background color which is very easy to do.
Good luck!

I think when you do postback the file contnet property will removed by default, because a security reasons !

Related

Error when opening a (silently) saved file c#

I have been making a text editor in c#, and recently added the functionality to silently save the file (without SaveFileDialog). The file appears to save properly, however, when trying to open the file, i get the error System.ArgumentException - File format is not valid. It opens fine if the file has not been saved silently.
The code:
The save method:
public void save(RichTextBoxPrintCtrl.RichTextBoxPrintCtrl rtbIn, string fileNameIn)
{
string fileName = "";
if (getFileFromMap(fileNameIn) != "")
{
// The file already exists in the Map so save it
fileName = getFileFromMap(fileNameIn);
StreamWriter writer = new StreamWriter(fileName);
writer.Write(rtbIn.Text);
writer.Close();
}
else
{
// The file does not exist in the Map so
// Send it to SaveAs with the rtb and the initial fileName passed in
saveAs(rtbIn, fileNameIn);
}
}
SaveAs:
public string saveAs(RichTextBoxPrintCtrl.RichTextBoxPrintCtrl rtbIn, string fileName)
{
saveDialog.FileName = fileName;
saveDialog.Title = "Save As";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
if (saveDialog.FileName.Length > 0)
{
if (saveDialog.FileName.EndsWith(".rtf"))
{
rtbIn.SaveFile(saveDialog.FileName, RichTextBoxStreamType.RichText);
}
else
{
rtbIn.SaveFile(saveDialog.FileName, RichTextBoxStreamType.PlainText);
}
addFileToMap(fileName, saveDialog.FileName);
return Path.GetFileName(saveDialog.FileName);
}
else { return ""; }
}
else { return ""; }
}
and Open:
public string open(RichTextBoxPrintCtrl.RichTextBoxPrintCtrl rtbIn)
{
if (openDialog.ShowDialog() == DialogResult.OK)
{
if (openDialog.FileName.Length > 0)
{
string fileName = Path.GetFileName(openDialog.FileName);
if (fileName.EndsWith(".rtf"))
{
rtbIn.LoadFile(openDialog.FileName, RichTextBoxStreamType.RichText);
}
else
{
rtbIn.LoadFile(openDialog.FileName, RichTextBoxStreamType.PlainText);
}
addFileToMap(openDialog.FileName, openDialog.FileName);
return fileName;
}
else { return ""; }
}
else { return ""; }
}
Other information:
The filenames are stored in a Dictionary because the editor has tabs.
RichTextBoxPrintCtrl is a custom RichTextBox that supports printing, it doesn't change anything relating to opening
The methods above are in a separate class which is why they require the richtextbox to be passed in.
If you need any other code, just let me know.
Any advice would be appreciated! Thanks in advance :)
EDIT:
Fixed, couldn't use StreamWriter.
Well, the issue seems to be that you are not saving the file in the same way.
When you perform a saveAs, you are calling rtb.SaveFile. In your silent save you are directly trying to save the rtb.Text to the file but that is probably not the correct format rtb.OpenFile is expecting.
I am no expert whatsoever in RichTextBox but spotting the difference when on method works and another similar one doesn't normally helps.
To expand a little more, Text returns only the plain text (no content formatting information). Your method save is saving as plain text any file, even if its a .rtf. Your Open method on the other hand will try to open an .rtf file as a formatted text, this can be causing the issues you are having.

C# Opening PDF in Webbrowser

i know this question seems simple but it is giving me a headache.
I have a programm from where i want to show a pdf and this works fine and dandy
but when i want to change the pdf it won't work.
The application has two two tabpages, one for the PDF and one for the design etc.
I can click on Print and a pdf is created and it loads.
When changing the pdf, because i changed something in the first tab, it doesn't delete the old one and it won't load the new pdf file.
Here is my code:
//The PdfFile variable is the path to the old pdf file
//and file variable is the path to the new pdf file
if (wbPdfViewer != null)
{
wbPdfViewer.AllowNavigation = true;
wbPdfViewer.Navigate(new Uri("http://www.google.de")); //this should navigate
wbPdfViewer.Url = new Uri("http://www.google.de"); //this is just a try
bool isallowed = wbPdfViewer.AllowNavigation; //check during debbuging if it is set
string url = wbPdfViewer.Url.ToString(); //see if it works during debbuging
}
if (pdfViewer.Document != null) //this is an optional viewer ... nevermind that
{
pdfViewer.Document.Close();
pdfViewer.Document.Dispose();
}
try
{
DHIO.File.Delete(PdfFile);
}
catch(Exception ex)
{
#if DEBUG
MessageBox.Show("PdfViewer 02002: Couldn't delete PDF file");
#endif
}
if (wbPdfViewer != null)
{
GC.Collect();
if (string.IsNullOrEmpty(file) || !DHIO.File.Exists(file))
return;
wbPdfViewer.Navigate(new Uri(file));
ShowNavigationControls();
return;
}
As you can see i want to delete the PdfFile and it shouldn't be in access because i changed the page (in a later version google.de is replaced with about:blank or something else).
So my question is how to change the URL so that my program isn't accessing the pdf file anymore ?
i tried it with the navigationComplete event but this won't fire
and as always thanks in advance
Set the wbPdfViewer.Url to null.

Outputting all text file titles to a textbox on Windows Form

Getting a bit stuck on a piece of code I'm trying to write and was hoping for a helping hand if anyone knows where I'm going wrong!
I have a simple Windows Form where I have a folder browser. The user will browse to a folder and any sub-folders within will then be searched for a text file that has the word "Passed" in the title (not the body of the text file itself). There will be files with "Passed" in from many different folders, and I want the functionality of the app to search through all sub-folders and return the all the files that have this in their name.
At present I have the following code:
private void searchButton_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please enter a path");
}
else
{
string[] allFiles = Directory.GetFiles(textBox1.Text, "*Passed*.*", SearchOption.AllDirectories);
string name = resultsText.Text;
foreach(string file in allFiles)
{
if (file.Contains("Passed"))
{
resultsText.Text = file;
}
}
}
}
However, in the resultsText texbox, it only returns 1 value. There are multiple files with "Passed" in their title and I would like to print them all to this textbox. Does anyone know where I may be going wrong and why I am only getting one file rather than all of them?
Also, this method seems to return the whole file path e.g.)
C:\Program Files\Test\abc\PassedTests.txt - does anyone know how I can trim the full path so it just returns the file name and extension?
Any help is greatly appreciated!
You need to append the text. At the moment, you're overwriting the previous value by using resultsText.Text = file;.
if (file.Contains("Passed"))
{
resultsText.AppendText(file);
}
What may be more performant would to use build your string using a StringBuilder and then assign that to the TextBox.
StringBuilder sb = new StringBuilder();
foreach(string file in allFiles)
{
if (file.Contains("Passed"))
{
sb.Append(file);
}
}
resultsText.Text = sb.ToString();
You have to change 1 line of code:
resultsText.Text = file;
To this:
resultsText.Text += file;
The + will append the text and not overwrite it.
this is the answer for your second question.
try this to get only the file name
Path.GetFileName(filepath)

Get file path from inputstream?

I am trying to get the last modified date from a file, but need its path? Could someone please show me how i can get the file path?
[HttpGet]
public string uploadfile(string token, string filenameP, DateTime modDate, HttpPostedFileBase file)
{
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
byte[] data = target.ToArray();
//ModDate = File.GetLastWriteTimeUtc("Path");
}
You are creating a new file on the server when you upload. The last modified date will be "now" (the time the file is created). There is no way to snoop the user's machine to get this information (which is not part of the file itself). Can't be done with an HTTP form upload.
Now, some file types may contain metadata in the file which may have pertinent information. If you know the file type and it does contain such metadata then you can open the file and have a look.
You just don't. Most (if not all) browsers do not provide this information for security reasons in internet sceanrios.
You can read date by javascript (HTML5) and send it as hidden input field of form.
Something like
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push(f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() );
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
http://www.html5rocks.com/en/tutorials/file/dndfiles/

File Uploading using Server.MapPath() and FileUpload.SaveAs()

I have a website admin section which I'm busy working on, which has 4 FileUpload controls for specific purposes. I need to know that , when I use the Server.MapPath() Method Within the FileUpload control's SaveAs() methods, Will it still be usable on the web server after I have uploaded the website? As far as I know, SaveAs() requires an absolute path, that's why I map a path with Server.MapPath()
if (fuLogo.HasFile) //My FileUpload Control : Checking if a file has been allocated to the control
{
int counter = 0; //This counter Is used to ensure that no files are overwritten.
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]); // This is the part Im wondering about. Will this still function the way it should on the webserver after upload?
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++; //Here the counter is put into action
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;
}
if (fuLogo.PostedFile.ContentLength > 409600 ) //File must be 400kb or smaller
{
cvValidation.ErrorMessage = "Please use a picture with a size less than 400 kb";
cvValidation.IsValid = false;
}
else
{
if (fuLogo.HasFile && cvValidation.IsValid)
{
fuLogo.SaveAs(logo); //Save the logo if file exists and Validation didn't fail. The path for the logo was created by the Server.MapPath() method.
}
}
}
else
{
logo = "N/A";
}
If you intend to save the files in
a directory on your web server , then
the Server.MapPath() will be the suitable
solution.
string dirPath = System.Web.HttpContext.Current.Server.MapPath("~") + "/Images/Logos/"+ fileBreak[0] + counter.ToString() + "." + fileBreak[1];
Look Here
if you intend to save your files out
the web server then
Use a full path, like "c:\uploads"
and be sure that the web process has
permission to write to that folder,I suggest you store the path itself in the web.config file in this case.
yes, that can be used after saving file and when you try retrieve that file...
Server.MapPath("~/Images/Logos/" + uploadedFileName);
Yes it should still work as Server.MapPath uses the relative values and returns the complete physical path.
It's one line of code:
FileUpload1.PostedFile.SaveAs(Server.MapPath(" ")+"\\YourImageDirectoryOnServer\\"+FileUpload1.FileName);

Categories

Resources