I'm trying to save a file that is uploaded using an HttpPostedFile control.
The main issue I'm running into, is that it won't create a new folder for the file.
In the code below, "file" is an HttpPostedFile.
So I have my base path that I define like this:
Dim basePath = "D:\\game\\world\\map\\MediaFiles\\"
Then I get the file name like this:
Dim fileName = Path.GetFileName(file.FileName)
Now I want to create a new path like this using the gameId (guid):
Dim newFolderAndFile As String = gameId + fileName
And then combine the path with the base path and save:
Dim saveAsPath = Path.Combine(basePath, newFolderAndFile)
file.SaveAs(saveAsPath)
But when I try that, I always get an error like this:
System.IO.DirectoryNotFoundException: Could not find a part of the
path
'D:\game\world\map\MediaFiles\05a10e9c-e8a9-49ed-ad4f-34b6b4650ef3\5.jpg'
So it looks like the saveAsPath is being constructed correctly, however SaveAs isn't saving it.
How can I get SaveAs to create the path and file?
Thanks!
As the_lotus explained, you need to create the directory first before saving the file
Dim basePath = "D:\game\world\map\MediaFiles\"
Dim fileName = Path.GetFileName(file.FileName)
' make new folder
system.io.direcotry.createdirectory(basepath & gameid)
Dim saveAsPath = (basePath & gameid & "\" & filename)
file.SaveAs(saveAsPath)
I'm not sure about the double slashes, I think that's not needed...
Related
I write the below code to copy the file and rename file name but the problem that i have now that i need to pick the last file (based on upload date) then rename the file , the below code change all files placed in the folder regardless the upload date , also if there is a simple code to upload file check if file is exist then show message (successful upload , failed upload (duplicate file))
Dim directory = Server.MapPath("App_Data/text/")
For Each filename As String In IO.Directory.GetFiles(directory, "*", IO.SearchOption.AllDirectories)
Dim fName As String = IO.Path.GetFileName(filename)
If fName.ToString Like "*Cust*" Then
System.IO.File.Delete(Server.MapPath("App_Data\test\Customer.txt"))
My.Computer.FileSystem.CopyFile(Server.MapPath("App_Data\text\" & fName), Server.MapPath("App_Data\test\" & fName))
My.Computer.FileSystem.RenameFile(Server.MapPath("App_Data\test\" & fName), "Customer.txt")
you can use below code and find creation date and last modified date of a file:
Dim creation as DateTime = File.GetCreationTime(#"C:\test.txt")
Dim modification as DateTime = File.GetLastWriteTime(#"C:\test.txt")
or by Importing System.IO and using this code:
Dim fi as FileInfo = new FileInfo("path")
Dim created = fi.CreationTime
Dim lastmodified = fi.LastWriteTime
i think the second one is better because you can put them in a collection easily and then sort them or compare them.
I want to have a function in my game manager that "clones" a game. So far I have all the cloning working except cloning the game media.
I want the media to clone/copy like this:
basePath + gameId + mediaFile
So a simple example would look like this:
--- original game
c:\inetpub\wwwroot\spac_rpg\MediaFiles\12\33d43636-275b-4b92-8778-cf591829103e.png
c:\inetpub\wwwroot\spac_rpg\MediaFiles\12\57ea0ad8-c69a-45e7-951e-d0325aa404ab.mov
becomes
--- new clone of the game (notice the different gameIds and the different GUID Ids for the media)
c:\inetpub\wwwroot\spac_rpg\MediaFiles\13\4427a554-b6a7-457a-b5ff-7c7cb7aee5bb.png
c:\inetpub\wwwroot\spac_rpg\MediaFiles\13\e9371c5d-eb47-4014-8380-204f7aff44fb.mov
So far I have this, which isn't much, but I'm kinda stuck on where to go next:
' copy each media file to new folder with new name
' new and old media file IDs
Dim newMediaId As Guid
Dim oldMediaId As Guid
Dim oldGameId As Int
' base path for game media
Dim basePath = "C:\inetpub\wwwroot\spac_rpg\MediaFiles\"
' new media folder
Dim newMediaFolder = Directory.CreateDirectory(basePath & newGameId)
' XXX ds is a dataset that is returned from the database with the old and new mediaIDs
For Each dr As DataRow In ds.Tables(0).Rows
oldMediaId = dr("oldMediaID")
newMediaId = dr("newMediaID")
Dim oldFile = (basePath & oldGameId & "\" & oldMediaId)
Dim clonedFile = (basePath & newGameId & "\" & newMediaId)
Next
Or maybe I'm trying to break this down to much and there's a much easier way of copying?
I just need to make sure that the new folder with the new GameId is created and that each new media file is cloned with the newMediaId that is returned from the database call.
Thanks!
The System.IO.File.Copy can do the copy for you. It takes the source file and destination file (which can be different) as parameters).
System.IO.File.Copy(oldFile, clonedFile)
could someone help me with this error??
I tried to save excel file using EPPlus
[IOException: The process cannot access the file 'C:\Users\Julian\Downloads\EmployeeMaster.xls' because it is being used by another process.]
here is my code :
Dim conn As New ConnectionVB
Dim newfile As FileInfo = NewFileInfo("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Using p As ExcelPackage = New ExcelPackage(newfile)
SetWorkBookProperties(p)
conn.connect()
Dim ws As ExcelWorksheet = CreateSheet(p, "EmnployeeMaster")
Dim dt As New DataTable
Dim connString As String
connString = "Select * from EmployeeMaster"
dt = conn.openDataTable(connString)
Dim rowIndex As Integer
rowIndex = 2
CreateHeader(ws, rowIndex, dt)
CreateData(ws, rowIndex, dt)
Dim bin As Byte()
bin = p.GetAsByteArray()
Dim path As String
path = "C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls"
File.Delete("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Dim stream As Stream = File.Create(path)
File.WriteAllBytes(path, bin) <- I got the error here
Start(path)
stream.Close()
End Using
Appriciate all help/advice with this error
Regards Siekh
As from your Error shows: EmployeeMaster.xls file is being used by another process.
Your code DryRun:
In your EmployeeMaster.xls file you make another new sheet name as EmnployeeMaster and then you create Header, and Data in this sheet.
problem arise when you write to file. you have to just save WorkSheet by doing .
because just open your .xls file with the help of EPPlusPackage and then by code Add your custom sheet in .xls file and just save.
p.Save(); // you need to save this temporary sheet.
Problems may be:
EPPLUS cannot open xls files, only xlsx files.
Why you delete File.
solution: you can rename and then move.
EPPlus hold your file when you instantiate object for ExcelPackage(with the same Path)
Two Problems:
EPPlus does not support xls files.
For debugging why the file is used, I recommend using SysInternal's "process explorer", you can find it here.
My sql query is returning records from the database that contains a filename. I will be appending the filepath (from the web.config file) to allow the user to download the complete file. However, another colum in the grid, has to be the file size.
How can I obtain the filesize, given that the name is being returned from the database, and the filepath is from the web.config file?
Thanks
One way to do it is to store the size of the pdf file upon your upload of the file to the server and then just retrieve it along with the file name.
Using System.IO you can get the filesize
Dim f As New FileInfo("thefullfilepath")
Dim i As Integer = f.Length
EDIT: Use Import System.IO for VB
string MyFile = "~/files/my.pdf";
FileInfo finfo = new FileInfo(Server.MapPath(MyFile));
long FileInBytes = finfo.Length;
long FileInKB = finfo.Length / 1024;
Use the FileInfo class:
' Build the string fileName from path stored in Web.Config and the filename
' returned from the database
Dim fileName As String = "your path and filename"
Dim fInfo As FileInfo = new FileInfo(fileName)
Dim fileSize As Long = fInfo.Length
You will probably need to do this in the RowDataBound event, assuming your binding your GridView to a datasource (like your SQL query).
I'm trying to delete all files in a folder which start with a specific user id so if the user id = 00000 then I want to delete file 00000-1.xml & 00000-2.xml & 00000-3.xml and so on.
I have this code so far:
Dim path as String = Server.MapPath("../myfolder/xml/00000" & something?? & ".xml")
If path <> "" Then
Dim fileInfo As FileInfo = Nothing
Try
fileInfo = New FileInfo(path)
If fileInfo.Exists Then
File.Delete(path)
End If
Catch
End Try
End If
Obviously I have just added the something?? in as i have no idea what to put there?
Can anyone shed any light on this?
Consider using Directory.GetFiles instead.
Dim path as String = Server.MapPath("../myfolder/xml")
If path <> "" Then
Dim fileName As String
For Each fileName in Directory.GetFiles (path, "00000-*.xml")
File.Delete(fileName)
Next
End If
You can also just enumerate through any files, if they exist like this (will need to convert to VB syntax):
foreach (string DeleteFileName in Directory.EnumerateFiles(Server.MapPath(#"../MyFolder/xml"), "00000*.xml"))
{
File.Delete(Path.Combine(Server.MapPath(#"../MyFolder/xml"), DeleteFileName));
}
Note, I don't recall offhand whether EnumberateFiles gives just the file name or the fullpath. if fullpath, you can drop the Path.Combine().
Using LINQ:
Directory.EnumerateFiles(Server.MapPath(#"../myfolder/xml", "0000*.abc")).ToList().ForEach(File.Delete);