ASP.NET/VB.NET FileUpload Control - asp.net

I have a problem with FileUpload, when I select a file from the local machine, it will not bring the real path of the file, it will use the path for the project files and assume the file I am selecting is there, any ideas?
Example:
File name is "Q.JPG" and is in "C:\"
when I browse to "C:\" and select "Q.JPG" and click open, I get the following Error
Could not find file 'C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\q.jpg'.
So when I fire up the code for Uploading the file to FTP for example, it will return an error because file doesn't exist
HTML side:
<asp:FileUpload ID="FU" runat="server" Height="24px" />
Below is the VB code:
Protected Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
If FU.PostedFile IsNot Nothing AndAlso FU.PostedFile.FileName <> "" Then
Dim MaxSize As Integer = FU.PostedFile.ContentLength
If MaxSize > "2097152" Then
lblUpload.Text = "The file size cannot exceed 2 MB"
btnSave.Focus()
GoTo 99
End If
'--------------------------
' set up request...
Dim LocFile As String = FU.PostedFile.FileName
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://myftp.com/" & LocFile), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("username", "password")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
' read in file...
Dim bFile() As Byte = System.IO.File.ReadAllBytes(FU.PostedFile.FileName)
' upload file...
Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Close()
clsStream.Dispose()
'--------------------------
lblUpload.Text = "Uploaded"
btnSave.Focus()
Else
lblUpload.Text = "Choose a file to upload"
btnSave.Focus()
End If
99: 'Do Nothing
End Sub

The problem is you're trying to read in the PostedFile as a local file (on the web server), not from the HttpPostedFile object attached to the FileUploader.
Try:
Dim objFileStream As System.IO.Stream = FU.PostedFile.InputStream
Dim bFile(objFileStream.Length) As Byte
objFileStream.Read(bFile, 0, objFileStream.Length)

I tried something, and it worked..
FU.SaveAs("C:\" & FU.FileName)
'--------------------------
' set up request...
Dim LocFile As String = FU.PostedFile.FileName
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("MyFTP.com" & LocFile), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("username", "password")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
It worked.. simply saved the file from FU (FileUpload) to C:\ and then setting the address to always start at C:\

Related

Search folder for file using the user input, then create copy of file

I am trying to create a simplistic program that will search for an image using the users input, in a specific folder, if the image exists, then creates a copy of that image to another folder. The user may not have the whole name, for example, the image name could be iStock-454565767, The user would be able to just input the numbers without the istock.
We use thousands of istock photos that have been purchased and are housing them in one file, which makes searching for specific images difficult, especially when we may need several at one time.
I have this code:
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim FSO, sourceFolder, currentFile, filesInSourceFolder
Dim strSourceFolderPath As String
Dim strDestinationFolderPath As String
Dim strUserInput As String
FSO = CreateObject("Scripting.FileSystemObject")
strUserInput = txtSearch.Text
strSourceFolderPath = "C:\Users\D41071023\Desktop\Photo Database"
strDestinationFolderPath = "C:\Users\D41071023\Desktop\test"
sourceFolder = FSO.GetFolder(strSourceFolderPath)
filesInSourceFolder = sourceFolder.Files
For Each currentFile In filesInSourceFolder
If currentFile.Name = strUserInput Then
currentFile.Copy(FSO.BuildPath(strDestinationFolderPath,
currentFile.Name))
End If
Next
End Sub
When I click "Search" nothing happens. No file is created, there's not even an error. Also, I want to add a message box that pops up when the file has been created, or a message that lets the user know that the image was not found.
Upto my understanding,
Dim sourceFolderPath = "source folder path here" ' Folderpath without spaces
Dim fileNumber = "file number here"
Dim sourceFilePath = Directory.GetFiles(sourceFolderPath, $"iStock-{fileNumber}.png").FirstOrDefault()
If Not IsNothing(sourceFilePath) Then
Dim destinationFolderPath = "destination folder path here" 'Folderpath without spaces
Dim sourceFileName = Path.GetFileName(sourceFilePath)
Dim destinationFilePath = Path.Combine(destinationFolderPath, sourceFileName)
File.Copy(sourceFilePath, destinationFilePath)
MsgBox("File " & "iStock-{fileNumber}.png" & " found.", MsgBoxStyle.OkOnly)
else
MsgBox("File not found . . . ", MsgBoxStyle.OkOnly + MsgBoxStyle.Information)
End If
If I'm understanding you correctly, this is the sort of thing that you should have:
Dim sourceFolderPath = "source folder path here"
Dim fileNumber = "file number here"
Dim sourceFilePath = Directory.GetFiles(sourceFolderPath, $"iStock-{fileNumber}.png").SingleOrDefault()
If sourceFilePath IsNot Nothing Then
Dim destinationFolderPath = "destination folder path here"
Dim sourceFileName = Path.GetFileName(sourceFilePath)
Dim destinationFilePath = Path.Combine(destinationFolderPath, sourceFileName)
File.Copy(sourceFilePath, destinationFilePath)
End If

VB.NET Get directory and sub-directory from path

I'm trying to get the full path minus the filename from a path in vb.net. I'm using a textbox and a browse button to get the full path, but I want to save just the directories.
How do I get just the directories and sub-directories?
Example file name:
c:\Users\jsmith\Desktop\file.aspx
Desired result:
c:\Users\jsmith\Desktop\
Protected Sub btnBackupFolderName_Click(sender As Object, e As EventArgs) Handles btnBackupFolderName.Click
' Call ShowDialog.
Dim result As DialogResult = openFD.ShowDialog()
' Test result.
If result = Windows.Forms.DialogResult.OK Then
Dim FileNameText As String = openFD.FileName.ToString()
Dim backupFolderName = Path.GetFileName(Path.GetDirectoryName(FileNameText)) 'this just gives me 'Desktop'
txtBackupFolder.Text = di.ToString 'backupFolderName
End If
End Sub
Thank you for your help!
Get the full path of the file and then use GetDirectoryName() to retrieve the folder-path, like this:
Dim openFD As OpenFileDialog = New OpenFileDialog()
Dim result As DialogResult = openFD.ShowDialog()
If result = DialogResult.OK Then
Dim FileNameText As String = openFD.FileName.ToString()
' This gets the folder-path, sans filename.
txtBackupFolder.Text = Path.GetDirectoryName(openFD.FileName)
End If

Docx File Corrupted after Upload

I have tired many things, searched the internet, and still I cannot figure out what is going on with this code. I still get that my docx files are corrupted, but when I do it with doc file everything is going great.
My Upload Code
Private Sub LbReqUploadAttachment1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbReqUploadAttachment1.Click
If FileUplReqAttachment1.HasFile Then
'Then save the attachment to the documents table
Dim type As String = Me.FileUplReqAttachment1.PostedFile.ContentType
Dim myFile As System.Web.HttpPostedFile = Me.FileUplReqAttachment1.PostedFile
Dim nFileLen As Integer = myFile.ContentLength
Dim myData(nFileLen) As Byte
myFile.InputStream.Read(myData, 0, nFileLen)
Dim DocDto As New DocumentsDto
DocDto.Month = Now.ToString("m")
DocDto.Year = Now.Year
DocDto.MimeType = type
DocDto.UploadedById = MyPage.LoggedOnUser.DtoUser.PersonId
DocDto.DocumentBytes = myData.ToArray
DocDto = MyPage.DelegateDocument.CreateDocumentsDto(DocDto)
'Update the order with the new document id
If Me.TbIntlFlagz.Checked Then
Item.AssetID = CStr(DocDto.DocumentID)
Else
Item.AssetID = "0"
End If
' Save Everything
SaveItem()
'Focus after postback
FileUplReqAttachment1.Focus()
End If
'Stay on order screen
Response.Redirect(String.Format("Default.aspx?i={0}&Item={1}", MyPage.DtoPage.PageID, Me.Item.Id))
End Sub
My download code:
Sub ProcessRequest(ByVal context As HttpContext) Implements ttpHandler.ProcessRequest
Dim docba As Byte() = docDto.DocumentBytes
Dim ext As String = Mime.GetExtensionFromMime(docDto.MimeType)
context.Response.ContentType = docDto.MimeType
If String.IsNullOrEmpty(ext) Then
'We can only use the attachment approach if we found a good extension based on the mime type
Else
Dim DispositionHeader As String
If Not context.Request.QueryString.Item("fn") Is Nothing Then
DispositionHeader = String.Format("attachment; filename={0}.{1}", AntiXss.UrlEncode(context.Request.QueryString.Item("fn")), ext)
Else
DispositionHeader = String.Format("attachment; filename={0}.{1}", AntiXss.UrlEncode("Document"), ext)
End If
context.Response.AppendHeader("Content-Disposition", DispositionHeader)
End If
context.Response.Expires = (60 * 24 * 1)
context.Response.OutputStream.Write(docba, 0, docba.Length)
context.Response.Flush()
docba = Nothing
End If
End Sub
I have tired these with no success:
Why are .docx files being corrupted when downloading from an ASP.NET page?
http://www.aspmessageboard.com/showthread.php?230778-Downloaded-docx-files-are-corrupted
https://social.msdn.microsoft.com/Forums/vstudio/en-US/88383fb2-03c6-49f5-afee-ce38497789bd/retrieving-docx-stored-in-sql-server-results-in-there-was-an-error-opening-the-file?forum=vbgeneral
I am uploading the file into a DB, and downloading the file by pressing a hyperlink. When I press the hyperlink and download the file. View at the file it is corrupted.
In VB, when declaring an array you give it the number of elements in the array. This is different from many languages where you specify the last index of the array.
For the code you show, you need to use
Dim myData(nFileLen - 1) As Byte
to make sure that you do not have an extra element in the array.
It appears that the .doc format is not sensitive to this, but .docx is.

Getting Error in Set the folder access?

Getting error “Some or all identity references could not be translated
Getting error in 8th line
Dim FolderPath As String = "D:\Account\HA\" 'Specify the folder here
Dim UserAccount As String = mailid.ToString() & "\" & pwd
Dim objDirectoryInfo As DirectoryInfo = Nothing
Dim objDirectorySecurity As DirectorySecurity = Nothing
Dim objRule As FileSystemAccessRule = Nothing
objDirectoryInfo = New DirectoryInfo(FolderPath)
objDirectorySecurity = objDirectoryInfo.GetAccessControl
objRule = New FileSystemAccessRule(UserAccount, FileSystemRights.ReadPermissions, AccessControlType.Allow)
objDirectorySecurity.AddAccessRule(objRule)
objDirectoryInfo.SetAccessControl(objDirectorySecurity)
Try these changes I have made up for you...
Public Sub AddDirectorySecurity(ByVal FolderPath As String, ByVal Account As String, ByVal Rights As FileSystemRights, ByVal ControlType As AccessControlType)
' Create a new DirectoryInfoobject.
Dim objDirectoryInfo As New DirectoryInfo(FolderPath)
' Get a DirectorySecurity object that represents the current security settings.
Dim objDirectorySecurity As DirectorySecurity = objDirectoryInfo.GetAccessControl()
' Add the FileSystemAccessRule to the security settings.
objDirectorySecurity .AddAccessRule(New FileSystemAccessRule(Account, Rights, ControlType))
' Set the new access settings.
objDirectoryInfo .SetAccessControl(dSecurity)
End Sub
Give this a shot and let me know how it works out for you?
Thanks!

How to create file on server with special privileges on Asp .net using visual basic?

One of the client requirements is that the server generate files and store them on a special folder. This files created can not be modified by users or deleted.
So the only way I thought is to generate this files with elevated privileges so a normal user can't delete or modify them.
But the question is how can I generate a file with this privileges that normal users can interact with this files... only download from server.
I use this code to generate the file... But I don't know how to configure it for elevated privileges.
This is the button which generate the file and allow to download it:
Protected Sub ibtGenerar_OnClick(ByVal sender As Object, ByVal e As ImageClickEventArgs)
oArchivoTelecredito.NombreArchivo = txtNombreArchivo.Text
oArchivoTelecredito.SesionDetalleArchivosTelecredito = New List(Of DetalleArchivoTelecreditoBE)
Dim oArchivoTelecreditoSL As New ArchivoTelecreditoSL
Response.AddHeader("Content-disposition", "attachment;filename=" & oArchivoTelecredito.NombreArchivo & ".txt")
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(oArchivoTelecreditoSL.GeneraArchivoTelecredito(oArchivoTelecredito, Server.MapPath(oArchivoTelecredito.NombreArchivo)))
Response.End()
End Sub
This is the function which create the file on server:
Public Function GeneraArchivoTelecredito(ByVal telecredito As ArchivoTelecreditoBE, ByVal ruta As String) As Byte()
Dim lineas As Integer = telecredito.SesionDetalleArchivosTelecredito.Count + 1
Dim registro(0 To lineas) As String
registro(0) = Me.ObtenerCabeceraArchivoTelecredito(telecredito)
Dim archivo = ruta & ".txt"
Using escritor As New StreamWriter(archivo)
For index = 0 To lineas
escritor.WriteLine(registro(index))
Next
escritor.Close()
End Using
Dim lector As FileStream
lector = File.Open(archivo, FileMode.Open)
Dim bytes(lector.Length) As Byte
lector.Read(bytes, 0, lector.Length)
lector.Close()
Return bytes
End Function
If you want to set the file to be read-only then you can use
File.SetAttributes("PathToFile", FileAttributes.ReadOnly).
You could also set the permissions on the directory itself instead of the individual files - see this post: https://serverfault.com/questions/3878/is-there-a-way-to-prevent-a-file-from-being-deleted

Resources