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);
Related
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...
I have got an issue where it would be super convenient to move whole folders instead of files.
I myself have 0 code writing experience with Blue Prism but went through the code to see if I can modify it to suit my needs.
When I run this code, I get this error message:
Second path fragment must not be a drive or UNC name.
Would anyone be able to have a look and advice on the mistakes I have made? Please bear in mind that it's a novice's work. Thank you in advance.
Inputs: Folder Path, Destination
Try
Dim sSourceFolder As String = Folder_Path
Dim sDestinationFolder As String
If Directory.Exists(Destination) Then
sDestinationFolder = Destination
If Not sDestinationFolder.EndsWith("\") Then
sDestinationFolder &= "\"
End If
sDestinationFolder = ""
Else
sDestinationFolder = ""
sDestinationFolder = Destination
End If
Dim objDirectoryInfo As DirectoryInfo = New DirectoryInfo(sSourceFolder)
Dim aFolders As DirectoryInfo() = objDirectoryInfo.GetDirectories(sSourceFolder)
For Each oFolder As DirectoryInfo In aFolders
If sDestinationFolder = "" Then
oFolder.MoveTo(sDestinationFolder)
Else
oFolder.MoveTo(sDestinationFolder)
End If
Next
Success = True
Message = ""
Catch e As Exception
Success = False
Message = e.Message
End Try
My solution creates a new folder in the destination with the same name as the source folder, copies its contents, and deletes the source folder (essentailly the same thing as moving it). The inputs remain Folder_Path and Destination:
Success = True
Message = ""
Try
If Not Folder_Path.EndsWith("\") Then
Folder_Path &= "\"
End If
Dim newDirectory As String = System.IO.Path.Combine(Destination, Path.GetFileName(Path.GetDirectoryName(Folder_Path)))
If Not (Directory.Exists(newDirectory)) Then
Directory.CreateDirectory(newDirectory)
End If
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(Folder_Path, newDirectory)
System.IO.Directory.Delete(Folder_Path, True)
Catch e As Exception
Success = False
Message = e.Message
End Try
Make sure that you include the System.IO namespace in the Code Options of your object. The Code Options can be found by double-clinking the description box on the Initialize Page/Action and choosing the appropriate tab.
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.)
i want to set a link in VB.net dynamically to a file.
My url looks like that:
http://server/folder/folder2/file.aspx?get=param
I tried to use Request.URL but i have not found any solution to get only
http://server/folder/folder2/
without the query string and without the filename.
Please help.
Dim url = Request.Url;
Dim result = String.Format(
"{0}{1}",
url.GetLeftPart(UriPartial.Authority),
String.Join(string.Empty, url.Segments.Take(url.Segments.Length - 1))
)
You can easily get a relative file path using the Request instance, then work with that, using Path class ought to help:
Dim relativePath = Request.AppRelativeCurrentExecutionFilePath
Dim relativeDirectoryPath = System.IO.Path.GetDirectoryName(relativePath)
It's worth noting that GetDirectoryName might transform your slashes, so you could expand the path:
Dim mappedPath = HttpContext.Current.Server.MapPath(newpath)
So, to remove redundancy, we could shorten this:
Dim path = _
Server.MapPath( _
Path.GetDirectoryName( _
Request.AppRelativeCurrentExecutionFilePath)))
But you'll need to check for possible exceptions.
You can use Uri.Host to get the computer name and then Uri.Segments (an array) to get everything up to the filename, for example:
var fileName = Uri.Host && Uri.Segments(0) && Uri.Segments(1)
This will give you: server/folder/folder2
If you have a variable number of segments, you can iterate over them and ignore the last one.
I hope that might help :)
I am trying to import some data from an excel spreadsheet, using VB.net
my steps are:
first the user uploads the file to the server
then i want to read the file from the server to then populate a gridview
this is what i have:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim filepath As String = ""
If FileUpload1.HasFile Then
Try
If (FileUpload1.PostedFile.ContentType = "application/vnd.ms-excel") Then
Dim filename As String = Path.GetFileName(FileUpload1.FileName)
'Session("userid") & "-" & Date.Now()
filepath = "\excel\" & Session("userid") & "_" & Now.Date().ToString("Mdy") & "_" & filename
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
ReadExcel(filepath)
Else
StatusLabel.Text = "Only Excel file types are accepted"
End If
Catch ex As Exception
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message
End Try
End If
End Sub
Sub ReadExcel(ByVal filepath As String)
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & filepath & "';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [NSTS]", MyConnection)
MyCommand.TableMappings.Add("Table", "Net-informations.com")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
gwResults.DataSource = DtSet.Tables(0)
MyConnection.Close()
End Sub
the error happens with "MyConnection", it tried to look on the "C:/" instead of on the server:
'c:\excel\3_41911_Sample.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
how can i set the OleDb connection to get the source file from the server instead?
thank you!
nevermind, i got it
i added: Server.MapPath("~/") & filepath and now it works. however, now i'm getting the error:
The Microsoft Jet database engine could not find the object 'NSTS'. Make sure the object exists and that you spell its name and the path name correctly.
NSTS is the name of my first spreadsheet. what am i doing wrong? :(
i was missing a studip dollar sign :) ahh, it all works now!
"select * from [NSTS$]"
thanks!
Use a $ in your sheet's name in the query:
"select * from [NSTS$]"
Your c:\excel\ path is not local path but it is path local to where you are running your application.
If you are running this application from local machine, In order to map c:\excel\ path, you should either map server drive to your windows and use that drive name OR use \\excel as path value.
First - do you know exactly where on the server path the file is being saved to? I'd begin by hardcoding the path to make sure that there isn't anything else squirrely going on.
Looking at your code you're saving the file here...
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
So... first, are you sure it's saving there? If so then look as where you're reading the file with this call...
ReadExcel(filepath)
Have you tried -
ReadExcel(Server.MapPath("~/") & filepath)?