I have a HR web application which includes organization structure within workplaces.
The client is sending a .docx file with workplace name and its description. I need to make a C# application to get data from the .docx file and update some database tables with it.
I already tried .docx conversion to XML but I have no idea how to pick up data from that XML and insert it into the database.
Is there a easier way to update this database directly from a .docx file or what mechanics should I use to find data in the XML file.
Try this..
Below is the connection string to the database. You can modify it to suit yours
<connectionStrings>
<add name="conString" connectionString="Data Source=.\SQLEXPRESS;database=dbFiles; Integrated Security=true"/>
</connectionStrings >
To start with I have added a FileUpload control, a button and a Label to show messages
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text=""
Font-Names = "Arial"></asp:Label>
And here is the snippet which is called on the Upload Button Click event
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
//Set the contenttype based on File Extension
switch(ext)
{
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
//insert the file into database
string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
" values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value
= contenttype;
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";
}
}
VB.Net
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
' Read the file and convert it to Byte Array
Dim filePath As String = FileUpload1.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
'Set the contenttype based on File Extension
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload1.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "insert into tblFiles" _
& "(Name, ContentType, Data)" _
& " values (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value _
= contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." _
& " Upload Image/Word/PDF/Excel formats"
End If
End Sub
The above code simply reads the uploaded File as Stream and then converts the Stream to Byte array using Binary Reader and then the finally the byte arrays is saved to the database InsertUpdateData method executes the query to save the data in database
The InsertUpdateData function is given below
C#
private Boolean InsertUpdateData(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
Related
I'm trying to post an image from local using LINE Notify, but get bad request, how to send the right request using HttpWebRequest with multipart/form-data content-type in vb.net?
I've tried on cURL, and it's woking:
curl -i -X POST https://notify-api.line.me/api/notify -H "Authorization: Bearer <TOKEN>" -F "message=test" -F "imageFile=#C:\PATH\to\file.jpg"
Here is what I've done in vb.net:
Imports System.IO
Imports System.Net
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
Private Sub btnPic_Click(sender As Object, e As EventArgs) Handles btnPic.Click
OpenFileDialog1.Filter = "Image File (*.jpg)|*.jpg;*.JPG |Image File (*.png)|*.png;*.PNG"
OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog() <> DialogResult.Cancel Then
txtPic.Text = OpenFileDialog1.FileName
End If
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
' [references]
'https://notify-bot.line.me/doc/en/
'http://white5168.blogspot.com/2017/01/line-notify-6-line-notify.html
'https://aprico-media.com/posts/1824
'https://stackoverflow.com/questions/3890754/using-httpwebrequest-to-post-data-upload-image-using-multipart-form-data
Dim md5Hash As MD5 = MD5.Create()
'Boundary string
Dim strBound As String = "---------------------" & GetMd5Hash(md5Hash, CInt(Int((654321 * Rnd()) + 1))).Substring(0, 10)
Try
Dim request = DirectCast(WebRequest.Create("https://notify-api.line.me/api/notify"), HttpWebRequest)
Dim postData As String = "--" & strBound & vbCrLf
postData += "Content-Disposition: form-data; name=""message""" & vbCrLf & vbCrLf
postData += txtText.Text & vbCrLf
' [Not working] sticker part
'postData += "--" & strBound & vbCrLf
'postData += "Content-Disposition: form-data; name=""stickerPackageId""" & vbCrLf & vbCrLf
'postData += 1 & vbCrLf
'postData += "--" & strBound & vbCrLf
'postData += "Content-Disposition: form-data; name=""stickerId""" & vbCrLf & vbCrLf
'postData += 2 & vbCrLf
If txtPic.Text <> "" Then
Dim ext As String = Path.GetExtension(txtPic.Text)
If ext = ".jpg" Then
ext = "jpeg"
ElseIf ext = ".png" Then
ext = "png"
Else
MessageBox.Show("Sorry! LINE Notify supports only jpeg/png image file.")
btnPic.PerformClick()
Return
End If
' [Not working] image part
postData += "--" & strBound & vbCrLf
postData += "Content-Disposition: form-data; name=""imageFile""; filename=""" & Path.GetFileName(txtPic.Text) & """" & vbCrLf
postData += "Content-Type: image/" & ext & vbCrLf & vbCrLf
postData += Convert.ToBase64String(File.ReadAllBytes(txtPic.Text)) & vbCrLf
End If
postData += vbCrLf & "--" & strBound & "--"
Dim data = Encoding.UTF8.GetBytes(postData)
request.Method = "POST"
request.ContentType = "multipart/form-data; boundary=" & strBound
request.ContentLength = data.Length
request.Headers.Add("Authorization", "Bearer <TOKEN>")
Using stream = request.GetRequestStream()
stream.Write(data, 0, data.Length)
End Using
Dim response = DirectCast(request.GetResponse(), HttpWebResponse)
Dim responseString = New StreamReader(response.GetResponseStream()).ReadToEnd()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End Sub
Shared Function GetMd5Hash(ByVal md5Hash As MD5, ByVal Input As String) As String
' Convert the input string to a byte array and compute the hash.
Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(Input))
' Create a new Stringbuilder to collect the bytes
' and create a string.
Dim sBuilder As New StringBuilder()
' Loop through each byte of the hashed data
' and format each one as a hexadecimal string.
Dim i As Integer
For i = 0 To data.Length - 1
sBuilder.Append(data(i).ToString("x2"))
Next i
' Return the hexadecimal string.
Return sBuilder.ToString()
End Function 'GetMd5Hash
End Class
There is no problem for sending only "message", whenever the other parts i.e."imageFile", "stickerPackageId", "stickerId",... are combined with, the result is getting error (400). However, if a field name is changed to small letter as i.e."stickerpackageid", "stickerid" vb will not catch any exception, but just send the "message" to Notify. So, I think a wrong part should be in http request string, or does it needed to convert each field into binary array? If that is the case how to obtain the right result?
POST multipart/form-data for line notify , need generate output byte array list by yourself
LINE Notify API Reference https://notify-bot.line.me/doc/en/
Upload File Class
public class FormFile
{
public string Name { get; set; }
public string ContentType { get; set; }
public string FilePath { get; set; }
public byte[] bytes { get; set; }
}
Test Data
private void multipartTest(string access_token)
{
Dictionary<string, object> d = new Dictionary<string, object>()
{
// message , imageFile ... name is provided by LINE API
{ "message", #"message..." },
{ "imageFile", new FormFile(){ Name = "notify.jpg", ContentType = "image/jpeg", FilePath="notify.jpg" }
}
};
string boundary = "Boundary";
List<byte[]> output = genMultPart(d, boundary);
lineNotifyMultipart(access_token, boundary, output);
}
C# Code
private void lineNotifyMultipart(string access_token, string boundary, List<byte[]> output)
{
try
{
#region POST multipart/form-data
StringBuilder sb = new StringBuilder();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(lineNotifyURL);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=Boundary";
request.Timeout = 30000;
// header
sb.Clear();
sb.Append("Bearer ");
sb.Append(access_token);
request.Headers.Add("Authorization", sb.ToString());
// note: multipart/form-data boundary must exist in headers ContentType
sb.Clear();
sb.Append("multipart/form-data; boundary=");
sb.Append(boundary);
request.ContentType = sb.ToString();
// write Post Body Message
BinaryWriter bw = new BinaryWriter(request.GetRequestStream());
foreach(byte[] bytes in output)
bw.Write(bytes);
#endregion
getResponse(request);
}
catch (Exception ex)
{
#region Exception
StringBuilder sbEx = new StringBuilder();
sbEx.Append(ex.GetType());
sbEx.AppendLine();
sbEx.AppendLine(ex.Message);
sbEx.AppendLine(ex.StackTrace);
if (ex.InnerException != null)
sbEx.AppendLine(ex.InnerException.Message);
myException ex2 = new myException(sbEx.ToString());
//message(ex2.Message);
#endregion
}
}
private void getResponse(HttpWebRequest request)
{
StringBuilder sb = new StringBuilder();
string result = string.Empty;
StreamReader sr = null;
try
{
#region Get Response
if (request == null)
return;
// HttpWebRequest GetResponse() if error happened will trigger WebException
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
sb.AppendLine();
foreach (var x in response.Headers)
{
sb.Append(x);
sb.Append(" : ");
sb.Append(response.Headers[x.ToString()]);
if (x.ToString() == "X-RateLimit-Reset")
{
sb.Append(" ( ");
sb.Append(CheckFormat.ToEpcohDateTimeUTC(long.Parse(response.Headers[x.ToString()])));
sb.Append(" )");
}
sb.AppendLine();
}
using (sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
sb.Append(result);
}
}
//message(sb.ToString());
#endregion
}
catch (WebException ex)
{
#region WebException handle
// WebException Response
using (HttpWebResponse response = (HttpWebResponse)ex.Response)
{
sb.AppendLine("Error");
foreach (var x in response.Headers)
{
sb.Append(x);
sb.Append(" : ");
sb.Append(response.Headers[x.ToString()]);
sb.AppendLine();
}
using (sr = new StreamReader(response.GetResponseStream()))
{
result = sr.ReadToEnd();
sb.Append(result);
}
//message(sb.ToString());
}
#endregion
}
}
public List<byte[]> genMultPart(Dictionary<string, object> parameters, string boundary)
{
StringBuilder sb = new StringBuilder();
sb.Clear();
sb.Append("\r\n--");
sb.Append(boundary);
sb.Append("\r\n");
string beginBoundary = sb.ToString();
sb.Clear();
sb.Append("\r\n--");
sb.Append(boundary);
sb.Append("--\r\n");
string endBoundary = sb.ToString();
sb.Clear();
sb.Append("Content-Type: multipart/form-data; boundary=");
sb.Append(boundary);
sb.Append("\r\n");
List<byte[]> byteList = new List<byte[]>();
byteList.Add(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));
foreach (KeyValuePair<string, object> pair in parameters)
{
if (pair.Value is FormFile)
{
byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
FormFile form = pair.Value as FormFile;
sb.Clear();
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(pair.Key);
sb.Append("\"; filename=\"");
sb.Append(form.Name);
sb.Append("\"\r\nContent-Type: ");
sb.Append(form.ContentType);
sb.Append("\r\n\r\n");
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
byteList.Add(bytes);
if (form.bytes == null && !string.IsNullOrEmpty(form.FilePath))
{
FileStream fs = new FileStream(form.FilePath, FileMode.Open, FileAccess.Read);
MemoryStream ms = new MemoryStream();
fs.CopyTo(ms);
byteList.Add(ms.ToArray());
}
else
byteList.Add(form.bytes);
}
else
{
byteList.Add(System.Text.Encoding.ASCII.GetBytes(beginBoundary));
sb.Clear();
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(pair.Key);
sb.Append("\"");
sb.Append("\r\n\r\n");
sb.Append(pair.Value);
string data = sb.ToString();
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
byteList.Add(bytes);
}
}
byteList.Add(System.Text.Encoding.ASCII.GetBytes(endBoundary));
return byteList;
}
I have been developing a service that will upload/download files to and from the AWS S3 Cloud Service. The following code runs fine, but I'm getting the error "Web exception with status Send failure was thrown" or "The underlying connection was closed: An unexpected error occurred on a send" more often than not. Please find below the list of links I checked. None of them seem to solve the issue. Any help would be appreciated.
Links I checked:
https://blogs.msdn.microsoft.com/jpsanders/2009/01/07/you-receive-one-or-more-error-messages-when-you-try-to-make-an-http-request-in-an-application-that-is-built-on-the-net-framework-2-0/
C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send
https://forums.asp.net/t/2037197.aspx?C+HttpWebRequest+The+underlying+connection+was+closed+An+unexpected+error+occurred+on+a+send+
Code to Upload:
Private Shared Function Upload(ByVal S3Key As String, ByVal bucketName As String, ByRef client As IAmazonS3, ByVal filePath As String) As String
Try
Dim putRequest As New PutObjectRequest
putRequest.BucketName = bucketName
putRequest.Key = S3Key
putRequest.FilePath = filePath
putRequest.Metadata.Add("x-amz-meta-title", "someTitle")
putRequest.Metadata.Add("Entity", "entity")
putRequest.Metadata.Add("DocumentType", "docType")
putRequest.Metadata.Add("UploadDate", DateTime.UtcNow.ToShortDateString())
putRequest.Metadata.Add("Content-Type", "contentType")
Dim response As PutObjectResponse = client.PutObject(putRequest)
Catch amazonS3Exception As AmazonS3Exception
If amazonS3Exception.ErrorCode IsNot Nothing AndAlso (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") OrElse amazonS3Exception.ErrorCode.Equals("InvalidSecurity")) Then
Return "Invalid AWS Credentials"
Else
Return "Error occurred. Message:'{0}' when writing an object" + amazonS3Exception.Message
End If
End Try
End Function
Code to Download:
Public Function AWSFileDownload(ByVal fname As String, ByVal strFileType As Int32) As String
Try
Dim path As Path
Dim data As String
Dim awsAccessKey = System.Configuration.ConfigurationManager.AppSettings("AWSACCESSKEY")
Dim awsSecretKey = System.Configuration.ConfigurationManager.AppSettings("AWSSECRETKEY")
Dim bucketName_Documents = System.Configuration.ConfigurationManager.AppSettings("bucketName_Documents")
Dim bucketName_OtherDocuments = System.Configuration.ConfigurationManager.AppSettings("bucketName_OtherDocuments")
Dim S3Key As String = fname
Dim type As String = ""
Dim dest As String = ""
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Using s3Client = New AmazonS3Client(awsAccessKey, awsSecretKey, RegionEndpoint.USEast1)
Dim request As New GetObjectRequest()
If (strFileType = "0") Then
request.BucketName = bucketName_OtherDocuments
ElseIf (strFileType = "1") Then
request.BucketName = bucketName_Documents
End If
request.Key = S3Key
Using response As GetObjectResponse = s3Client.GetObject(request)
Dim ext = Path.GetExtension(S3Key)
If Not IsDBNull(ext) Then
ext = LCase(ext)
End If
Select Case ext
Case ".htm", ".html"
type = "text/HTML"
Case ".txt"
type = "text/plain"
Case ".doc", ".rtf"
type = "Application/msword"
Case ".csv", ".xls"
type = "Application/x-msexcel"
Case ".docx"
type = "Application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Case ".xlsx"
type = "Application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Case Else
type = "text/plain"
End Select
dest = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), S3Key)
If Not File.Exists(dest) Then
response.WriteResponseStreamToFile(dest)
End If
End Using
End Using
Response.ClearHeaders()
Response.AppendHeader("content-disposition", "attachment; filename=" + S3Key)
If type <> "" Then
Response.ContentType = type
End If
Response.WriteFile(dest)
Response.End()
Catch amazonS3Exception As AmazonS3Exception
If amazonS3Exception.ErrorCode IsNot Nothing AndAlso (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId") OrElse amazonS3Exception.ErrorCode.Equals("InvalidSecurity")) Then
Return "Invalid AWS Credentials"
Else
Return "Error occurred. Message:'{0}' when writing an object" + amazonS3Exception.Message
End If
End Try
End Function
I tried the below code to upload a file to sql server table using vb.net command button. But while clicking build getting error in UploaderEventArgs.
Type 'UploaderEventArgs' is not defined.
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Protected Sub UploadAttachments1_FileUploaded(ByVal sender As Object, ByVal args As UploaderEventArgs)
'set connection string
Dim connectionString As String = System.Configuration.ConfigurationSettings.AppSettings("ConnectionString")
' Read the file and convert it to Byte Array
Dim data() As Byte = New Byte((args.FileSize) - 1) {}
'get file extension
Dim extensioin As String = args.FileName.Substring((args.FileName.LastIndexOf(".") + 1))
Dim fileType As String = ""
'set the file type based on File Extension
Select Case (extensioin)
Case "doc"
fileType = "application/vnd.ms-word"
Case "docx"
fileType = "application/vnd.ms-word"
Case "xls"
fileType = "application/vnd.ms-excel"
Case "xlsx"
fileType = "application/vnd.ms-excel"
Case "jpg"
fileType = "image/jpg"
Case "png"
fileType = "image/png"
Case "gif"
fileType = "image/gif"
Case "pdf"
fileType = "application/pdf"
End Select
Dim stream As Stream = args.OpenStream
'read the file as stream
stream.Read(data, 0, data.Length)
Dim con As SqlConnection = New SqlConnection(connectionString)
Dim com As SqlCommand = New SqlCommand
com.Connection = con
'set parameters
Dim p1 As SqlParameter = New SqlParameter("#Name", SqlDbType.VarChar)
Dim p2 As SqlParameter = New SqlParameter("#FileType", SqlDbType.VarChar)
Dim p3 As SqlParameter = New SqlParameter("#Data", SqlDbType.VarBinary)
p1.Value = args.FileName
p2.Value = fileType
p3.Value = data
com.Parameters.Add(p1)
com.Parameters.Add(p2)
com.Parameters.Add(p3)
com.CommandText = "Insert into Files (Name,FileType,Data) VALUES (#Name,#FileType,#Data)"
con.Open()
'insert the file into database
com.ExecuteNonQuery()
con.Close()
End Sub
End Class
Source Link to the above code:
http://ajaxuploader.com/h/Save-Files-to-Database-using-FileUpload-Control.htm
It looks like UploaderEventArgs is part of the framework the company you linked offers, so you need to download and install it first. It's not part of the regular .NET libraries.
We've been using an IIS filehandler to download files that are stored in a database such as PowerPoint. Now we're trying to switch to webapi. File uploads are working fine but downloads are not.
Using the filehandler the url is like: http://localhost:57851/docmgr?id=6202 which returns a valid file with the following info from Fiddler:
Using the same code in a webapi controller having a url of: http://localhost:57851/webapi/file/GetFile?id=6202 returns a file with additional bytes added. Fiddler data:
Note the change in content-type as well even though the content-type is expressly set to "application/vnd.ms-powerpoint".
I must be missing something....
Here is the controller code:
<HttpGet>
Public Function GetFile()
Dim dbConn As New SqlConnection(DigsConnStr)
Dim dbCmd As New SqlCommand
Dim dbRdr As SqlDataReader
Dim id As String = HttpContext.Current.Request.QueryString("id")
Dim bytes As Byte()
Dim contentType As String
Dim fileName As String
Dim fileExt As String
Try
dbConn.Open()
dbCmd.Connection = dbConn
dbCmd.CommandText = "GET_FileForDownload"
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.Parameters.AddWithValue("#VirtualFileRecID", id)
dbRdr = dbCmd.ExecuteReader
dbRdr.Read()
contentType = dbRdr("ContentType")
bytes = dbRdr("FileBytes")
fileExt = dbRdr("FileExtension")
If contentType <> "" Then
fileName = dbRdr("Title") & fileExt
HttpContext.Current.Response.ContentType = contentType
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
HttpContext.Current.Response.BinaryWrite(bytes)
'HttpContext.Current.Response.Flush()
End If
dbConn.Close()
Catch ex As Exception
dbConn.Close()
Finally
If Not (dbConn Is Nothing) Then dbConn.Close()
End Try
End Function
WebAPI is going to wrap your response in XML (or whatever formatter you have in your webapiconfig class)
You really shouldn't access the response stream directly with WebAPI but you can return a HttpResponseMessage object with the file stream
Check this out
<HTTPGET>
Public Function GetFile(FileID as Integer) As HttpResponseMessage
Dim path = "C:\Temp\test.exe"
Dim result As New HttpResponseMessage(HttpStatusCode.OK)
Dim stream = New FileStream(path, FileMode.Open)
result.Content = New StreamContent(stream)
result.Content.Headers.ContentType = New MediaTypeHeaderValue("application/octet-stream")
Return result
End Function
Then you should really access it like this: http://localhost:57851/docmgr/6202
I am using the following code for creating the folder on FTP server ; But its not working in my case :-
Dim sFilePath as string =filepath
Dim ftpResponse1 As FtpWebResponse
Dim ftpRequest1 As FtpWebRequest
Dim IsExists1 As Boolean = True
ftpRequest1 = CType(FtpWebRequest.Create(sFilePath), FtpWebRequest)
ftpRequest1.UseBinary = True
ftpRequest1.Credentials = New NetworkCredential(ZXFTPUSER, ZXFTPPASS)
ftpRequest1.UsePassive = True
ftpRequest1.Method = WebRequestMethods.Ftp.MakeDirectory
'ftpRequest1.KeepAlive = False
'ftpResponse1 = ftpRequest1.GetResponse()
'ftpResponse1 = ftpRequest1.GetResponse()
'Dim strstream1 As Stream = ftpResponse1.GetResponseStream()
'Dim strreader1 As New StreamReader(strstream1)
'Console.WriteLine(strreader1.ReadToEnd())
'strreader1.Close()
'strstream1.Close()
'ftpResponse1.Close()
Please help me.
In the above case i am not getting any error but when i am going to upload a rar file then it is giving the following exception
The remote server returned an error: (550) File unavailable (e.g., file not found, no access).
And File Upload code is given below
Public Sub FTPUpload(ByVal SourceFile() As IO.FileInfo, ByVal folderLevel As Integer, ByVal ftpPassiveMode As Boolean)
ZXFTPPASS = "******"
Dim filePath As New IO.DirectoryInfo(filePaths)
Dim ftpRequest As FtpWebRequest
Dim dResult As Windows.Forms.DialogResult
Dim ftpFilePath As String = ""
Dim levelPath As String = ""
Dim iLoop As Integer
Dim uFile As IO.FileInfo
For Each uFile In SourceFile
Try
ftpFilePath = levelPath & "/" & uFile.Name
ftpRequest = CType(FtpWebRequest.Create(ftpFilePath), FtpWebRequest)
ftpRequest.Credentials = New NetworkCredential(ZXFTPUSER, ZXFTPPASS)
ftpRequest.UsePassive = ftpPassiveMode
ftpRequest.UseBinary = True
ftpRequest.KeepAlive = False
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
'Read in the file
Dim b_file() As Byte = System.IO.File.ReadAllBytes(filePath.FullName & "\" & uFile.Name.ToString())
'Upload the file
Dim cls_stream As Stream = ftpRequest.GetRequestStream()
cls_stream.Write(b_file, 0, b_file.Length)
cls_stream.Close()
cls_stream.Dispose()
'MsgBox("Uploaded Successfully", MsgBoxStyle.Information)
Catch
MsgBox("Failed to upload.Please check the ftp settings", MsgBoxStyle.Critical)
End Try
Next
End Sub
Looking through various sites I have found this:
Private Function FtpFolderCreate(folder_name As String, username As String, password As String) As Boolean
Dim request As Net.FtpWebRequest = CType(FtpWebRequest.Create(folder_name), FtpWebRequest)
request.Credentials = New NetworkCredential(username, password)
request.Method = WebRequestMethods.Ftp.MakeDirectory
Try
Using response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
' Folder created
End Using
Catch ex As WebException
Dim response As FtpWebResponse = DirectCast(ex.Response, FtpWebResponse)
' an error occurred
If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
Return False
End If
End Try
Return True
End Function
this is working code on how to create a directory on a FTP server Via Vb.net
Dim folderName As String = "POP/" & Date.Now.Year.ToString & Date.Now.Month.ToString.PadLeft(2, "0"c) & Date.Now.Day.ToString.PadLeft(2, "0"c)
Dim RequestFolderCreate As Net.FtpWebRequest = CType(FtpWebRequest.Create("ftp://" & server & "/" & folderName), FtpWebRequest)
RequestFolderCreate.Credentials = New NetworkCredential(username, password)
RequestFolderCreate.Method = WebRequestMethods.Ftp.MakeDirectory
Try
Using response As FtpWebResponse = DirectCast(RequestFolderCreate.GetResponse(), FtpWebResponse)
End Using
Catch ex As Exception//catch a expection