how to move file another folder using asp - asp.net

how to move existing file to another folder using asp, but i will send file series "scn_1" only
FROM -- > d:\image\scn_1_1.jpg , d:]image\scn_1_2.jpg
TO --> d:\image2\backup\scn_1_1.jpg, scn_1_2.jpg
in asp or vb
this is my sample code
Dim fs
fs = Server.CreateObject("Scripting.FileSystemObject")
Dim scanpath = Request.QueryString("spath")
Dim rkpath = Request.QueryString("rkpath")
Dim series = Request.QueryString("series")
fs.MoveFile("D:\Ethiraj\ScanDcocument\scanimage\test.txt", "D:\Ethiraj\ScanDcocument\Rk_Images\test.txt")
fs = Nothing

Dim fs fs = Server.CreateObject("Scripting.FileSystemObject") Dim scanpath = Request.QueryString("virtu_dir") Dim rkpath = Request.QueryString("RK_path") Dim series = Request.QueryString("series") Dim fileToFind = series & "*.jpg" Dim dirs As String() = IO.Directory.GetFiles(scanpath, fileToFind) Dim dir As String For Each dir In dirs If dir.Contains(series) Then Dim filename = System.IO.Path.GetFileName(dir) fs.CopyFile(dir, rkpath + "\" + filename) fs = Nothing End If Next

Related

How can I stop Ionic zip from appending null to the end of a file

I have a VB.net (ASPX) which receives a file (data stream) from my application, and depending on switches will save the file as is or compress & encrypt it using ionic.zip. When a file is saved without encryption it is byte perfect. When the same file is compressed/encrypted and then decrypted/uncompressed there is an extra null (ascii(0)) character appended to the end of the decrypted file. This is generally not an issue, but MS Office products complain about corrupted files (then opens them fine).
The code I use is fairly straightforward and I cannot see any issues. I found nothing in my searches for this issue with ionic zip. Here is the code;
<%# Page Language="VB" validateRequest="false"%>
<%# Import Namespace="Ionic.Zip"%>
<%# Import Namespace="System.Web.HttpContext"%>
<script Runat="Server">
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim strToken As String = Request.QueryString("token")
Dim strSessionID As String = Request.QueryString("SessionID")
Dim strAlternateFileName As String = Request.QueryString("AlternateFileName")
Dim strDestinationFolder As String = Request.QueryString("DestinationFolder")
Dim strZipYN As String = Request.QueryString("ZipYN")
Dim strZipFileName As String = Request.QueryString("ZipFileName")
Dim strZipPassword As String = Request.QueryString("ZipPassword")
Dim fileName As String = System.IO.Path.GetFileName(Request.Files(0).FileName)
If IsNothing(Current.Session("token" & strSessionID)) _
Then
Current.Session("token") = strToken
Current.Session("token" & strSessionID) = Current.Session("token")
End If
If Len(strAlternateFileName) > 0 _
Then
fileName = strAlternateFileName
End If
If strZipYN <> "Y" _
Then
Request.Files(0).SaveAs(Server.MapPath(strDestinationFolder + "/") + fileName)
Else
Dim fileIn As HttpPostedFile
Dim objZipFile As ZipFile = New ZipFile
fileIn = Request.Files(0)
Dim intFileInLen = fileIn.ContentLength
Dim bytFielIn(intFileInLen) As Byte
Dim strmFileIn As System.IO.Stream
strmFileIn = fileIn.InputStream
strmFileIn.Read(bytFielIn, 0, intFileInLen)
If strZipPassword.Length > 0 _
Then
objZipFile.Password = strZipPassword
objZipFile.Encryption = EncryptionAlgorithm.WinZipAes256
End If
objZipFile.AddEntry(fileName, bytFielIn)
objZipFile.SaveSelfExtractor(Server.MapPath(strDestinationFolder + "/") + strZipFileName + ".exe", SelfExtractorFlavor.WinFormsApplication)
' objZipFile.SaveSelfExtractor(Server.MapPath(strDestinationFolder + "/") + strZipFileName + ".zip", SelfExtractorFlavor.WinFormsApplication)
objZipFile.Dispose()
objZipFile = Nothing
'Create a PW protected ZIP only for non windows computers.
objZipFile = New ZipFile
If strZipPassword.Length > 0 _
Then
objZipFile.Password = strZipPassword
objZipFile.Encryption = EncryptionAlgorithm.WinZipAes256
End If
objZipFile.AddEntry(fileName, bytFielIn)
objZipFile.Save(Server.MapPath(strDestinationFolder + "/") + strZipFileName + ".zip")
objZipFile.Dispose()
objZipFile = Nothing
End If
End Sub
</script>
Any ideas?
Edit:
I get the same results whether I extract the file from the ".exe" file, or the ".zip" file

ssrs to byte and byte to pdf in memory

I am trying to copy ssrs report to pdf in memory but i am getting error message when i open pdf 'file not in right format' . I am using asp.net and iTextSharp.
I want to copy ssrs to new pdf (rptpdf) file in memory and then open existing pdf and copy images to second page of that (rptpdf) pdf.
For testing purpose i am trying to see if i can copy ssrs to pdf.
Dim doc As New iTextSharp.text.Document()
Dim content As Byte()
Try
Using myMemoryStream As New MemoryStream()
Dim writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, myMemoryStream)
doc.Open()
Dim cb As iTextSharp.text.pdf.PdfContentByte = writer.DirectContent
Dim page As iTextSharp.text.pdf.PdfImportedPage
'--- bytes = rptViewer.ServerReport.Render("PDF", "", "", "", "", Nothing, Nothing)
Dim b() As Byte = ReportRender.GetReport()
Dim reader2 As New iTextSharp.text.pdf.PdfReader(b)
Dim pages As Integer = reader2.NumberOfPages
For i As Integer = 1 To pages
doc.SetPageSize(iTextSharp.text.PageSize.LETTER)
doc.NewPage()
page = writer.GetImportedPage(reader2, i)
cb.AddTemplate(page, 0, 0)
Next
doc.Close()
reader2.Close()
writer.Close()
content = myMemoryStream.ToArray()
myMemoryStream.Close()
End Using
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=" & "hello" & ".pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Write(content)
UPDATED
I have managed to copy reportviewer report byte to memory stream but at add pdf file (line "writer.AddPage(page)") i get error 'object not reference '
Using myMemoryStream As New MemoryStream()
Dim rptpdfwriter As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, myMemoryStream)
If rptpdfwriter Is Nothing Then
Return
End If
doc.Open()
Dim cb As iTextSharp.text.pdf.PdfContentByte = rptpdfwriter.DirectContent
Dim page2 As iTextSharp.text.pdf.PdfImportedPage
'--- bytes = rptViewer.ServerReport.Render("PDF", "", "", "", "", Nothing, Nothing)
Dim b() As Byte = ReportRender.GetReport()
Dim reader2 As New iTextSharp.text.pdf.PdfReader(b)
Dim pages2 As Integer = reader2.NumberOfPages
For i As Integer = 1 To pages2
doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate)
doc.NewPage()
page2 = rptpdfwriter.GetImportedPage(reader2, i)
cb.AddTemplate(page2, 0, 0)
Next
reader2.Close()
For Each item As Expenses In expenses
Select Case item.Ext.ToLower
Case ".pdf"
Dim writer As New iTextSharp.text.pdf.PdfCopy(doc, myMemoryStream)
Dim reader As New iTextSharp.text.pdf.PdfReader(Server.MapPath("/docs/expenses/" + item.ExpenseID.ToString + item.Ext))
reader.ConsolidateNamedDestinations()
For i As Integer = 1 To reader.NumberOfPages
Dim page As iTextSharp.text.pdf.PdfImportedPage = writer.GetImportedPage(reader, i)
writer.AddPage(page)
Next
Dim form As iTextSharp.text.pdf.PRAcroForm = reader.AcroForm
If form IsNot Nothing Then
writer.CopyAcroForm(reader)
End If
reader.Close()
Case ".jpg"
Dim pdfWriter As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, myMemoryStream)
Dim jpg As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(Server.MapPath("/docs/expenses/" + item.ExpenseID.ToString + item.Ext))
If Not doc.IsOpen Then doc.Open()
doc.Add(jpg)
Case Else
Exit Sub
End Select
Next
doc.Close()
Content = myMemoryStream.ToArray()
myMemoryStream.Flush()
myMemoryStream.Dispose()
Response.ContentType = "application/pdf"
Response.AppendHeader("Content-Disposition", "attachment; filename=LeftCorneraaa.pdf")
Response.BinaryWrite(Content)
End Using

Initiating an Dynamic Multidimensional Array in VB.net

I am receiving a "Object reference not set to an instance of an object." Error when trying to populate the fileDetails array. I am new to vb.net and I am lost.
Public Sub FindAllOrphanFiles(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
' Process the list of files found in the directory.
Dim files As String
Dim iCount As Integer = 0
Dim fileDetails As String(,)
For Each files In fileEntries
Dim fileIcon As String
Dim thisFile As New IO.FileInfo(files)
Dim fileName As String = thisFile.Name
Dim fileSize As String = thisFile.Length
Dim fileDateModified As String = thisFile.LastWriteTime
Dim fileExtension As String = Path.GetExtension(fileName)
Dim fileShortPath As String = Replace(Replace(files, uploadFolderPath, ""), fileName, "")
Dim fileFullPath As String = files
If fileExtension = ".pdf" Then
fileIcon = "acrobat"
Else
fileIcon = "paint"
End If
' Write to Array
fileDetails(iCount, 0) = fileIcon
fileDetails(iCount, 1) = fileName
fileDetails(iCount, 2) = fileShortPath
fileDetails(iCount, 3) = fileDateModified
fileDetails(iCount, 4) = fileSize
fileDetails(iCount, 5) = fileFullPath
iCount += 1
Next files
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
FindAllOrphanFiles(subdirectory)
Next subdirectory
End Sub 'FindAllOrphanFiles
Any help would be greatly appreciated.
Your array is not initialized. If you know the size at some point before your loop, you should initialize it using REDIM:
Dim fileDetails As String(,)
redim fileDetails(fileEntries.Count -1,5)
For Each files In fileEntries
....
If you don't know it ahead of time, use Redim Preserve inside you loop:
Dim fileDetails As String(,)
Dim I as int32 = -1
For Each files In fileEntries
I += 1
redim preserve fileDetails(i,5)
....

itextsharp pdfsmartcopy only returning last page

I have an issue where only the last page of my pdf is stored.
The pdf should be multiple pages long, and this works fine if I just send the pdf to the browser using Response and the mms memory stream, however I need to add it as a pdf to an email and therefore are writing mms to bytes to create a new memorystream when I create my email attachment. This is to get around the closed stream error.
This is my code
Public Shared Function SendPrePackLabels(ByVal bf_id As String, mail As String) As Boolean
Dim pars(0) As SqlParameter
pars(0) = New SqlParameter("#bf_id", SqlDbType.VarChar) With {.Value = bf_id}
Dim p As String
Dim reader As PdfReader
Dim mms As New MemoryStream
Dim rt() As Byte
Dim i As Integer = 0
Using dc As Document = New Document
Using sc As PdfSmartCopy = New PdfSmartCopy(dc, System.Web.HttpContext.Current.Response.OutputStream)
dc.Open()
With SqlHelper.ExecuteDataset(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spPrepack_Labels", pars).Tables(0)
For Each dr As DataRow In .Rows
Dim pdfr As New PdfReader("http://192.168.0.221/template.pdf")
Using ms As New MemoryStream
Using pdfs As New PdfStamper(pdfr, ms)
Dim fields As AcroFields = pdfs.AcroFields
fields.GenerateAppearances = True
fields.SetField("pono", dr.Item("po_no").ToString)
fields.SetField("ref", dr.Item("alt_code").ToString)
fields.SetField("colour", dr.Item("colour").ToString)
fields.SetField("code", dr.Item("sizerun_hdr_id").ToString)
For k As Integer = 1 To dr.Table.Columns.Count - 6
Dim j As Integer = k + 5
fields.SetField("s" & k, dr.Table.Columns(j).ColumnName.ToString)
If dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString = "" Then
p = "0"
Else
p = dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString
End If
fields.SetField("p" & k, p)
Next
fields.SetField("pack", dr.Item("sizerun_hdr_id").ToString)
Dim bcfont As BaseFont = BaseFont.CreateFont("http://192.168.0.221/ean.ttf", BaseFont.CP1252, BaseFont.EMBEDDED)
fields.SetFieldProperty("barcode", "textfont", bcfont, Nothing)
fields.SetFieldProperty("barcode", "textsize", 60.0F, Nothing)
Dim mBarcode As String = "219" & dr.Item("sizerun_hdr_id").ToString
Dim cLength As Integer = mBarcode.Length
Dim zerostoadd As Integer = 12 - cLength
Dim digit12barcode As String = mBarcode.PadRight(12, CChar("0"))
Dim FinalBarcode As String = returnCheckDigitedBarcode(digit12barcode)
fields.SetField("barcode", FinalBarcode)
Dim par(1) As SqlParameter
par(0) = New SqlParameter("#sizerun_hdr_id", SqlDbType.VarChar) With {.Value = dr.Item("sizerun_hdr_id").ToString}
par(1) = New SqlParameter("#ean13", SqlDbType.VarChar) With {.Value = FinalBarcode}
SqlHelper.ExecuteScalar(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spSizeRunEAN13", par)
pdfs.FormFlattening = True
ms.Flush()
End Using
reader = New PdfReader(ms.ToArray)
sc.AddPage(sc.GetImportedPage(reader, 1))
mms = ms
End Using
Next
End With
End Using
End Using
Dim bt() As Byte = mms.ToArray
Try
If mail.Length > 0 Then
Dim eMsg As New MailMessage()
eMsg.From = New MailAddress("myemail#mydomain.co.uk")
eMsg.To.Add(New MailAddress(mail))
Dim title As String = "<h3>Here are the Prepack Labels.</h3>"
eMsg.Subject = "Prepack Labels"
eMsg.Body = "<html>" & title & "</html>"
eMsg.IsBodyHtml = True
Dim att As Attachment = New Attachment(New MemoryStream(bt), "Prepack Labels.pdf", "application/pdf")
eMsg.Attachments.Add(att)
Dim SMTP1 As New SmtpClient
SMTP1.Host = "EX"
SMTP1.Send(eMsg)
att.Dispose()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function
I'm not sure of your exact problem but I'm pretty sure your life would be easier if you broke you giant function into smaller more specific functions that do only one thing. Also, I really recommend never writing to the raw ASP.Net stream until after you've created a PDF. Instead, always write to a MemoryStream, grab the bytes and do something with them.
The code below break it into four functions. CreatePdf() loops through the database and calls CreateSinglePdf() for each row in the table, merging them with your PdfSmartCopy. SendEmail() is blissfully unaware of iTextSharp completely and just receives a raw array of bytes that is assumed to be a PDF. This is all kicked off by SendPrePackLabels() which is where you'd probably want to also Response.BinaryWrite() your bytes.
Public Shared Function SendPrePackLabels(ByVal bf_id As String, mail As String) As Boolean
Dim bt = CreatePdf(bf_id)
Return SendEmail(bt, mail)
End Function
Public Shared Function CreateSinglePdf(dr As DataRow) As Byte()
Using ms As New MemoryStream
Using pdfr As New PdfReader("http://192.168.0.221/template.pdf")
Using pdfs As New PdfStamper(pdfr, ms)
Dim fields As AcroFields = pdfs.AcroFields
fields.GenerateAppearances = True
fields.SetField("pono", dr.Item("po_no").ToString)
fields.SetField("ref", dr.Item("alt_code").ToString)
fields.SetField("colour", dr.Item("colour").ToString)
fields.SetField("code", dr.Item("sizerun_hdr_id").ToString)
Dim p As String
For k As Integer = 1 To dr.Table.Columns.Count - 6
Dim j As Integer = k + 5
fields.SetField("s" & k, dr.Table.Columns(j).ColumnName.ToString)
If dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString = "" Then
p = "0"
Else
p = dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString
End If
fields.SetField("p" & k, p)
Next
fields.SetField("pack", dr.Item("sizerun_hdr_id").ToString)
Dim bcfont As BaseFont = BaseFont.CreateFont("http://192.168.0.221/ean.ttf", BaseFont.CP1252, BaseFont.EMBEDDED)
fields.SetFieldProperty("barcode", "textfont", bcfont, Nothing)
fields.SetFieldProperty("barcode", "textsize", 60.0F, Nothing)
Dim mBarcode As String = "219" & dr.Item("sizerun_hdr_id").ToString
Dim cLength As Integer = mBarcode.Length
Dim zerostoadd As Integer = 12 - cLength
Dim digit12barcode As String = mBarcode.PadRight(12, CChar("0"))
Dim FinalBarcode As String = returnCheckDigitedBarcode(digit12barcode)
fields.SetField("barcode", FinalBarcode)
Dim par(1) As SqlParameter
par(0) = New SqlParameter("#sizerun_hdr_id", SqlDbType.VarChar) With {.Value = dr.Item("sizerun_hdr_id").ToString}
par(1) = New SqlParameter("#ean13", SqlDbType.VarChar) With {.Value = FinalBarcode}
SqlHelper.ExecuteScalar(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spSizeRunEAN13", par)
pdfs.FormFlattening = True
End Using
End Using
Return ms.ToArray()
End Using
End Function
Public Shared Function CreatePdf(ByVal bf_id As String) As Byte()
Dim pars(0) As SqlParameter
pars(0) = New SqlParameter("#bf_id", SqlDbType.VarChar) With {.Value = bf_id}
Using ms As New System.IO.MemoryStream
Using dc As Document = New Document
Using sc As PdfSmartCopy = New PdfSmartCopy(dc, ms)
dc.Open()
With SqlHelper.ExecuteDataset(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spPrepack_Labels", pars).Tables(0)
For Each dr As DataRow In .Rows
Dim pageBytes = CreateSinglePdf(dr)
Using reader = New PdfReader(pageBytes)
sc.AddPage(sc.GetImportedPage(reader, 1))
End Using
Next
End With
End Using
End Using
Return ms.ToArray()
End Using
End Function
Public Shared Function SendEmail(bt As Byte(), mail As String) As Boolean
Try
If mail.Length > 0 Then
Dim eMsg As New MailMessage()
eMsg.From = New MailAddress("myemail#mydomain.co.uk")
eMsg.To.Add(New MailAddress(mail))
Dim title As String = "<h3>Here are the Prepack Labels.</h3>"
eMsg.Subject = "Prepack Labels"
eMsg.Body = "<html>" & title & "</html>"
eMsg.IsBodyHtml = True
Dim att As Attachment = New Attachment(New MemoryStream(bt), "Prepack Labels.pdf", "application/pdf")
eMsg.Attachments.Add(att)
Dim SMTP1 As New SmtpClient
SMTP1.Host = "EX"
SMTP1.Send(eMsg)
att.Dispose()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function

changing the way of coding so that MS Excel is not to be needed to installed on server in asp.net

I have started to deveop a website using asp.net.
I need to fetch some data from excel to display it to the client.
I am hosting my site on somee.com so that I can freely host it.
But on the server of somee.com Excel is not installed.
I have written some code for my website to display the data from from excel.
Dim xlApp As New Microsoft.Office.Interop.Excel.Application()
Dim xlWorkbook As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Open(FileUploadPath & sender.text)
Dim xlWorksheet As Microsoft.Office.Interop.Excel._Worksheet = xlWorkbook.Sheets(SheetName)
Dim xlRange As Microsoft.Office.Interop.Excel.Range = xlWorksheet.UsedRange
Dim rowCount As Integer = xlRange.Rows.Count
Dim colCount As Integer = xlRange.Columns.Count
Dim tbl As New DataTable()
For i As Integer = 1 To rowCount
tbl.Rows.Add()
Next
For i As Integer = 1 To colCount
tbl.Columns.Add()
Next
If rowCount > 1 Or colCount > 1 Then
For i As Integer = 1 To rowCount
For j As Integer = 1 To colCount
tbl.Rows(i - 1)(j - 1) = xlRange.Value2(i, j)
Next j
Next i
End If
gvReadFiles.AutoGenerateColumns = True
gvReadFiles.DataSource = tbl
gvReadFiles.DataBind()
xlApp.ActiveWorkbook.Close(False, Session(FileUploadPath & sender.text))
xlApp.Quit()
xlWorkbook = Nothing
xlApp = Nothing
Now I need to have some changes in code so it is not excel dependent.
Can you help me?
I solved it using google for more than 2 hours.
Here is the code
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
Dim connString As String = ""
If Extension = "xls" Or Extension = ".xls" Then
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 8.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""
ElseIf Extension = "xlsx" Or Extension = ".xlsx" Then
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 12.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""
End If
objConn = New OleDbConnection(connString)
objConn.Open()
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim firstSheetName As String = "Sheet1"
If Not dt Is Nothing Then
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
' Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
firstSheetName = row("TABLE_NAME").ToString().Substring(0, row("TABLE_NAME").ToString.Length - 1)
Exit For
Next
End If
Return firstSheetName
Catch ex As Exception
Return "Sheet1"
Finally
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try

Resources