Hi I am having some problems with saving img files using Visual Basic, the files are being named wrongly with the folder name being added to the start of the file name.
I parse a web address and then use the split address values to rename my files however the the path value seems to be added to the file as well.
The files in the photo should be named for example "DCAT040iMBE Test13.jpg"
but this file is being name "Test1DCAT040iMBE Test13.jpg"
Protected Sub GeneratedCode()
Dim path As String = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\"
LogoUpload.SaveAs(path + LogoUpload.FileName)
TextFile.SaveAs(path + TextFile.FileName)
Dim lines() As String = IO.File.ReadAllLines(path + TextFile.FileName)
For Each line As String In lines
Dim count As Integer
Dim encoder As New QRCodeEncoder()
encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H
encoder.QRCodeScale = 10
Dim img As Bitmap = encoder.Encode(line)
Dim logo As System.Drawing.Image = System.Drawing.Image.FromFile(path + LogoUpload.FileName)
Dim left As Integer = (img.Width / 2) - (logo.Width / 2)
Dim top As Integer = (img.Height / 2) - (logo.Height / 2)
Dim g As Graphics = Graphics.FromImage(img)
Dim parseLine = line
Dim replaceDelimiter As String
If Not String.IsNullOrWhiteSpace(line) Then
replaceDelimiter = Replace(line, "&", "=")
End If
Dim fileNameSplit() As String = replaceDelimiter.Split("=")
Dim newFileName As String
Dim partTwo = fileNameSplit(1)
Dim partSix = fileNameSplit(5)
Dim objFSO
Dim newFolder As String
newFolder = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\" + partSix
objFSO = CreateObject("Scripting.FileSystemObject")
If (Not System.IO.Directory.Exists(newFolder)) Then
System.IO.Directory.CreateDirectory(newFolder)
End If
count += 1
g.DrawImage(logo, New Point(left, top))
newFileName = partTwo & " " & partSix & count & ".jpg"
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
amountCreatedLbl.Text = count & " QRCodes Created"
logo.Dispose()
Next
End Sub
Could it be that I am generating my newFolder Values wrongly?
edited to add an example of data from the parsed txt file.
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test
Looks like you are missing a slash on the line:
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
It should be:
img.Save(newFolder + "\" + newFileName, ImageFormat.Jpeg)
The program doesn't realize that the newDirectory variable is supposed to be a directory, it's just being concatenated to the filename directly. A better option would be to use:
img.Save(System.IO.Path.Combine(newFolder, newFileName), ImageFormat.Jpeg)
The System.IO.Path.Combine() function automatically adds the missing slash between the directory and filename, as well as some additional checks to make sure the result is valid.
As a side note, I would also recommend using & instead of + when joining strings together. Hard to debug issues can come up when you do it that way. I would also recommend turning Option Strict On, you will see a couple of other warnings that come up with your code as is. But, to resolve your issue, the above will work.
Related
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
I am using the OpenXML library to auto generate Word files. I have a function that takes a group of files and merges them into one document. As I merge a new file into a document, I want each file to start on a new page. But, I don't want to have any blank pages. The code I have mostly works, but an issue comes up is if a file being merged in is a filled page, then a page break is still added, resulting in an empty page being added. I am not sure how to best deal with this, to prevent blank pages from being added. Here is my code:
Public Sub MergeFiles(ByVal filePaths As List(Of String), ByVal fileName As String)
Dim newFile As String = HttpRuntime.AppDomainAppPath & "PDF_Templates\TempFolder\catalog-" & Guid.NewGuid.ToString & ".docx"
File.Copy(fileName, newFile)
Dim counter As Integer = 0
For Each filePath As String In filePaths
Dim wordDoc As WordprocessingDocument = WordprocessingDocument.Open(newFile, True)
Using wordDoc
Dim mainPart As MainDocumentPart = wordDoc.MainDocumentPart
Dim altChunkId As String = "altChunkId" & counter
Dim chunk As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId)
Dim fileStream As FileStream = File.Open(filePath, FileMode.Open)
Using fileStream
chunk.FeedData(fileStream)
End Using
Dim AltChunk As AltChunk = New AltChunk()
AltChunk.Id = altChunkId
' Dont add a page break to the first page.
If counter > 0 Then
Dim last As OpenXmlElement = wordDoc.MainDocumentPart.Document.Body.Elements().LastOrDefault(Function(e) TypeOf e Is Paragraph OrElse TypeOf e Is AltChunk)
last.InsertAfterSelf(New Paragraph(New Run(New Break() With {
.Type = BreakValues.Page
})))
End If
mainPart.Document.Body.InsertAfter(Of AltChunk)(AltChunk, mainPart.Document.Body.Elements(Of Paragraph).Last())
mainPart.Document.Save()
wordDoc.Close()
End Using
counter = counter + 1
Next
End Sub
I do not have any experience with Unix coding besides navigating through directories and was wondering if someone could help me with writing a script to replicate what I am doing within .NET. I was told it would run faster since the .NET code is deployed remotely and sometimes using a mapped drive to access large amounts of folders runs slow. I basically am sorting files by moving files from selected folders to a group of folders based on the filename and sorting each based on the file date which is included in the filename.
Private Sub moveAllfiles(ByVal directoryStuff As String)
Dim templist As New ArrayList
Dim finalDestination As String = String.Empty
Dim pathName As String = String.Empty
Dim fileToDelete As String = String.Empty
Dim folderDate As String = String.Empty
Dim counter As Integer = 0
Dim folders = Directory.EnumerateDirectories(directoryStuff)
For Each item In folders
Dim files As String() = Directory.GetFiles(item)
//' if directory is empty delete folder
If Directory.GetFiles(item).Count = 0 Then
Directory.Delete(item)
Continue For
End If
For i As Integer = 0 To files.Count - 1
Try
counter += 1
Dim oInfo As New FileInfo(files(i))
// ' if file is empty or small delete it
If oInfo.Length <= 1 Then
File.Delete(files(i))
Continue For
End If
If Not files(i).EndsWith(".gz") Then
CompressFiles(files(i))
Continue For
End If
Dim objInfo As New FileInfo(files(i))
If Not objInfo.Name.Contains("Data_G_E") Then
If objInfo.Name.Contains("Data_G_P") Then
Dim pfiledate As String = objInfo.Name.Remove(20)
pfiledate = pfiledate.Remove(7, 5)
Dim ftempDirectory As String
= "M:\Archive\DataP\" + pfiledate & "\"
If Not Directory.Exists(ftempDirectory) Then
Directory.CreateDirectory(ftempDirectory)
Dim destdirectory As String = ftempDirectory
Dim ff As String = files(i)
fileToDelete = ff
File.Move(ff, destdirectory + objInfo.Name)
File.Delete(ff)
Else
Dim destdirectory As String = ftempDirectory
Dim ff As String = files(i)
fileToDelete = ff
File.Move(ff, destdirectory + objInfo.Name)
File.Delete(ff)
End If
End If
Continue For
End If
Dim filedate As String = objInfo.Name.Remove(20)
filedate = filedate.Remove(7, 5)
Dim tempDirectory As String = String.Empty
tempDirectory = "M:\Archive\DataE\" + filedate & "\"
If Not Directory.Exists(tempDirectory) Then
Directory.CreateDirectory(tempDirectory)
Dim destdirectory As String = tempDirectory
Dim ff As String = files(i)
fileToDelete = ff
File.Move(ff, destdirectory + objInfo.Name)
File.Delete(ff)
Else
Dim destdirectory As String = tempDirectory
Dim ff As String = files(i)
fileToDelete = ff
File.Move(ff, destdirectory + objInfo.Name)
File.Delete(ff)
End If
Catch ex As Exception
If ex.Message.Contains("already exists") Then
File.Delete(fileToDelete)
Console.WriteLine("DELETING OLD FILE " & fileToDelete)
End If
Continue For
End Try
Next
Next
End Sub
Not sure if the logic makes sense but basically it searches all subfolders for files. Strips the filename to get the date and name which indicates where the file should go. Use the date to create a folder in the destination directory and move files accordingly. If someone can help get started or propose a better way to do this I would really appreciate it.
Not looking too closely (indeed, hardly at all) at your .NET code, it looks like you want to find all of the files in or below a given directory, extract a string from a fixed position in the filename to use as a destination directory, and then move each file to that directory. If that is indeed what you are trying to do, it is fairly simple. To move each file in or below the directory /p/a/t/h to /path2/xxx where xxx is taken from positions 7 to 10 in the file name (I selected the indexes 7 and 10 randomly), just do:
find /p/a/t/h -type f -exec sh -c 'd="/path2/${0:7:3}";
mkdir -p "$d"; mv -i "$0" "$d"' {} \;
The -i flag to mv will cause an interactive prompt if you are overwriting any files, and is here as a safety catch to help prevent the unwary from blowing away files. (But you, the reader, would never execute any code that you don't fully understand, so this is not necessary!) You may want to replace it with a -f or just remove it. Also note that the double quotes are only necessary if your filenames are pathological. (For example, if they contain whitespace.)
In my project I am creating a CSV file, but I want to change it's design. Please help me:
Private Sub ExportDataToCSV()
Dim fileName As String = "CheckRegistrationStatus_" & Format(Now, "yyyyMMddhhmms") & ".csv"
HttpContext.Current.Response.Clear()
' Set the response headers to fit our CSV file
HttpContext.Current.Response.ContentType = "text/plain"
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)
Using writer As New System.IO.StreamWriter(HttpContext.Current.Response.OutputStream)
Dim columnHeader As String = String.Empty
For i As Integer = 0 To grd1.Columns.Count - 1
columnHeader += grd1.Columns(i).HeaderText & IIf(i < grd1.Columns.Count - 1, ",", "").ToString()
Next
writer.WriteLine(columnHeader)
'writer.WriteLine(AddCSVHeaderRow()) ' Only if you need custom headers to be added
' Add all the data rows
For Each row As GridViewRow In grd1.Rows
writer.WriteLine(GetCSVLine(row.Cells))
Next
End Using
' End the current response. Otherwise, excel will open with the whole page inside.
HttpContext.Current.Response.End()
End Sub
Private Shared Function GetCSVLine(ByVal cellsToAdd As TableCellCollection) As String
Dim line As String = String.Empty
Dim isFirst As Boolean = True
For Each cell As TableCell In cellsToAdd
If Not isFirst Then
line += ","
End If
isFirst = False
line += """" & Replace(cell.Text, " ", "") & """"
Next
Return line
End Function
Output is being displayed as shown in the following image. But I want to make the header bold and expand the column width . Please help me.
You cannot. The CSV file format is a data-only format. It provides no way to set fonts, column widths or anything else related to styling.
In addition, I don't think your code handles all data correctly. For example, if there's a comma within the data or a double quote, special steps are required. Here's some code I published for creating CSV files in C#.
If you want to produce a formatted Excel document, either in addition to your CSV file or in place of it, you could have a look at the Excel interop libraries.
http://msdn.microsoft.com/en-us/library/bb386107%28v=vs.90%29.aspx
http://support.microsoft.com/kb/301982
http://msdn.microsoft.com/en-us/library/aa188489%28office.10%29.aspx
Is there an equivalent to PHP's get_included_files in classic ASP?
No, there is not.
A very ugly function for that:
<!--#include file="include/common.asp"-->
<%
Function GetIncludedFiles()
Dim Url
Dim Fso
Dim Fs
Dim Src
Dim Arr
Dim Ret
Dim i
Set Fso = Server.CreateObject("Scripting.FileSystemObject")
ReDim Ret(-1)
Url = Request.ServerVariables("URL")
Set Fs = Fso.OpenTextFile(Server.MapPath(Url))
Src = Fs.Readall()
Fs.Close
Set Fs = Nothing
Set Fso = Nothing
Arr = Split(Src, "<" & "!--#include file=")
For i = 0 To UBound(Arr)
Arr(i) = Left(Arr(i), InStr(Arr(i), "-->"))
Arr(i) = Replace(Arr(i), "-", "")
Arr(i) = Replace(Arr(i), "'", "")
Arr(i) = Trim(Replace(Arr(i), """", ""))
If Arr(i) <> "" Then
ReDim Preserve Ret(UBound(Ret) + 1)
Ret(UBound(Ret)) = Arr(i)
End If
Next
GetIncludedFiles = Ret
End Function
Dim File
For Each File In GetIncludedFiles()
Response.Write File & "<br />"
Next
%>
The simple way is to create a main file in a specific directory (for example /include/mainfile.asp) and then include all the other files to this file. Something like:
<!#include File="[your directory here/file1.asp]"-->
<!#include File="[your directory here/file2.asp]"-->
<!#include File="[your directory here/file3.asp]"-->
Then, You can include your main file using "virtual" to the rest of your pages that you want to access those other included files.
<!#include Virtual="/include/mainfile.asp"-->
Not as such, but I vaguely remember seen a tool or two floating around that will give you the equivalent report. It might have been on Code Project or somewhere similar... its been a long time since I last ran across it.