Delete file in windows 7 using VB.NET - windows

I have written following code in vb.net to delete the file.
If File.Exists(strPath & "\ReportEng.ini") = True Then
File.SetAttributes(strPath & "\ReportEng.ini", FileAttributes.Normal)
File.Delete(strPath & "\ReportEng.ini")
End If
File.Copy("\\192.168.0.1\SAP_Shared\AddonExtra\ReportEng.ini", strPath & "\ReportEng.ini")
This code works perfectly in windows xp. But in Windows 7,I can not delete it. This OS is hectic OS from developer's point of view. Some or other problem occurs and Microsoft has not considered the developer while building this OS.
How do I delete file in Windows 7 ?

It's so easy to do so;
If My.Computer.FileSystem.FileExists("C:\somefile.ext") Then 'Check whether file exists
My.Computer.FileSystem.DeleteFile("C:\somefile.ext") 'Delete the file!
End If
Have a nice day!

You don't need to delete the file: there is an overload File.Copy Method (String, String, Boolean) which allows overwriting.
You didn't say what error you get. I suspect it is because the user doesn't have write access to the directory. You should probably be using a subdirectory of the directory returned by Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) or maybe .LocalApplicationData, and definitely not the directory containing the program.
Also, using Path.Combine(strPath, "ReportEng.ini") is how you're meant to combine paths - it'll take care of, e.g., the trailing path separator for you.

The preferred method for interfacing with the Windows file system uses the following namespace:
Imports Microsoft.VisualBasic.FileIO.FileSystem
To delete a file:
Dim FileLocation As String = strPath & "\ReportEng.ini"
If Not GetDirectoryInfo(FileLocation).Exists Then
GetFileInfo(FileLocation).Delete()
End If

Related

Embed a bash shell script in an AppleScriptObjC application with Xcode

I have attempted to follow the instructions on this post but I am falling short of understanding how some of the posters instructions work.
I want to be able to package the app with a prewritten bash script and then execute it, but don't follow from Step 4 onwards.
Post writes:
4. Also in your AppleScriptObjC script, add the following where appropriate:
property pathToResources : "NSString" -- works if added before script command
5. Where appropriate, also add the following in your AppleScriptObjC script:
set yourScript to pathToResources & "/yourScriptFile.sh"
-- gives the complete unix path
-- if needed, you can convert this to the Apple style path:
set yourScriptPath to (((yourScript as text) as POSIX file) as alias)`
6. As an aside, you could then open the file for read using
tell application "Finder"
open yourScriptPath
end tell
Questions:
Where do I add the line:
property pathToResources : "NSString"
Do I add which of the following, and where?
set yourScript to pathToResources & "/yourScriptFile.sh"
OR
set yourScriptPath to (((yourScript as text) as POSIX file) as alias)
How is it possible to execute the script itself? The mention As an aside, you could then open the file for read using only covers the Apple style path, it does not cover using the aforementioned style.
Can anyone shed a bit more light on this for me, or post a static copy of a AppDelegate.applescript file that shows how the original poster required the base code to be used? I have tried his method and looked across the internet for the past 3 weeks to no avail. I don't want to have to convert all my code for specific tools from bash scripts into AppleScript, as this would take a lot of work.
I only need to know how to reference to the script file (for example myBashScript.sh) in my app, which would reside in the application and be included by Xcode at time of compilation.
I think you should use the command path to resource <specifiedResource>.
See Standard Additions, path to resource.
You could set it by set myVariableName to path to resource "myBashScript.sh" or just use the command instead of your property so it points always to the right place (a user could move your app while running... lol).
ADDITION:
I did it that way in my AppleScript-Application:
on run_scriptfile(this_scriptfile)
try
set the script_file to path to resource this_scriptfile
return (run script script_file)
end try
return false
end run_scriptfile
Whenever I want to run a script that is bundled within my app I do this:
if my run_scriptfile("TestScript.scpt") is false then error number -128
run_scriptfile(this_scriptfile) returns true when everything worked.
I ended up bringing all the information together and now have a solution.
This takes into consideration the following facts:
firstScript = variable name that points to a script called scriptNumberOne.sh
scriptNumberOne.sh = the script that I have embedded into my application to run
ButtonHandlerRunScript_ = the name of the Received Action in Xcode
pathToResources = variable that points to the internal Resources folder of my application, regardless of it's current location
Using this information, below is a copy of a vanilla AppDelegate.applescript in my AppleScriptObjC Xcode project:
script AppDelegate
property parent : class "NSObject"
property pathToResources : "NSString"
on applicationWillFinishLaunching_(aNotification)
set pathToResources to (current application's class "NSBundle"'s mainBundle()'s resourcePath()) as string
end applicationWillFinishLaunching_
on ButtonHandlerRunScript_(sender)
set firstScript to pathToResources & "/scriptNumberOne.sh"
do shell script firstScript
end ButtonHandlerRunScript_
on applicationShouldTerminate_(sender)
-- Insert code here to do any housekeeping before your application quits
return current application's NSTerminateNow
end applicationShouldTerminate_
end script

VBS RegRead doesn't return value

I've got the following code:
Dim objShell,failing_path,working_path
failing_path = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Test"
working_path = "HKEY_LOCAL_MACHINE\SOFTWARE\7-zip\Path"
Set objShell = WScript.CreateObject("WScript.Shell")
WScript.Echo "Working: " & objShell.RegRead(working_path)
WScript.Echo "Not Working: " & objShell.RegRead(failing_path)
When executing I will get the Path from the 7-zip Registrykey, but the Test Key returns following error:
Error says: Registry wasn't opened for reading.
Here the proof that the Test-Key exists:
What am I doing wrong? I also tried to read the key via oReg.GetStringValue but this always returned null.
It seems like your script is running in a 32-Bit compatible scripting host but in a 64-bit OS.
Since 32 bit applications are automatically redirected to the WOW6432Node areas of the registry in 64-Bit OSes, RegRead method tries to read 32-Bit equivalent path like
HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Test
instead
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Test
So, if the redirected path does not exist you receive that error as expected.
You may need to force run your scripts in 64-bit compatible scripting hosts to get rid of that kind of implicit registry redirects.
When I tested this, I was able to read from non-Wow6432Node paths just fine, even when using a 32-bit cscript.exe from a 32-bit cmd.exe (Process Explorer showed image type 32-bit for both processes).
Perhaps it's something really simple? I was able to reproduce the behavior you described when I created a registry value with a spurious trailing space:
>>> key = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
>>> WScript.Echo sh.RegRead(key & "Test")
Unable to open registry key "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\
Uninstall\Test" for reading. (0x80070002)
>>> WScript.Echo sh.RegRead(key & "Test ")
asd

Permission denied on CopyFile in VBS

I'm trying to automate pushing a file into my users' home directories, but am stuck on a "Permission Denied" error — is thrown on line 6 here, with the CopyFile call.
There are other parts of the script (not shown) that create and copy folder contents using the same source and destination directories, and they work perfectly. It's only when I use CopyFile that it fails.
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists("H:\Minecraft\.minecraft\options.txt") Then
fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\"
End If
Set fso = Nothing
H: is a network home directory, to which the current user has full read/write privs.
I've tried adding/removing trailing slashes from the paths, adding "options.txt" to the destination path, removing the false argument... Not sure what else to try. Any thoughts?
FYI, this chunk of code, which comes immediately before the error-prone bit above, executes perfectly every time:
If Not fso.FolderExists("H:\Minecraft\.minecraft\bin\") Then
If Not fso.FolderExists("H:\Minecraft\.minecraft\") Then
fso.CreateFolder("H:\Minecraft\.minecraft\")
End If
fso.GetFolder("C:\Minecraft\bin\").Copy "H:\Minecraft\.minecraft\"
End If
I've only ever seen CopyFile fail with a "permission denied" error in one of these 3 scenarios:
An actual permission problem with either source or destination.
Destination path is a folder, but does not have a trailing backslash.
Source file is locked by an application.
for me adding / worked at the end of location of folder.
Hence, if you are copying into folder, don't forget to put /
Based upon your source variable (sourcePath = "C:\Minecraft\bin\") I suspect your hard code is pointing at the wrong place
fso.CopyFile "C:\Minecraft\options.txt", destinationPath, false
should be
fso.CopyFile "C:\Minecraft\bin\options.txt", destinationPath
or
fso.CopyFile sourcePath & "options.txt", destinationPath
Another thing to check is if any applications still have a hold on the file.
Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.
In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."
I have read your problem, And i had the same problem. But af ter i changed some, my problem "Permission Denied" is solved.
Private Sub Addi_Click()
'On Error Resume Next
'call ds
browsers ("false")
Call makeAdir
ffgg = "C:\Users\Backups\user\" & User & "1\data\"
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.Getfolder("c:\users\Backups\user\" & User & "1\data")
f.Attributes = 0
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Call fso.Copyfile(filetarget, ffgg, True)
Look at ffgg = "C:\Users\Backups\user\" & User & "1\data\", Before I changed it was ffgg = "C:\Users\Backups\user\" & User & "1\data" When i add backslash after "\data\", my problem is solved. Try to add back slash. Maybe solved your problem. Good luck.
You can do this:
fso.CopyFile "C:\Minecraft\options.txt", "H:\Minecraft\.minecraft\options.txt"
Include the filename in the folder that you copy to.
It's worth checking task manager for any stray wscript.exe tasks that are stuck.
It could be one of those that's blocking access to the file.
It is possible that your Antivirus software may be preventing the activity of the script. I encountered this with AVG Antivirus running in silent mode (which means it does not alert you to every protection step it takes, so you get a permission error without realising that AVG is preventing the action).
In my case, I invoked verbose mode (switched off silent mode), executed the script and AVG came up with an interception warning, allowing me to train AVG to permit this script to run.

Client-Side VBScript application, Incorrect Current Working Directory

I'm not understanding this behavior. Maybe someone can explain to me why my current working directory is not what I expect.
On my desktop, I have a folder called STKGui:
C:\Documents and Settings\Lauren\Desktop\STKGui
Located in that directory are the following files: gui.html, style.css, save.html, load.html Within STKGui there are also the following directories: Images, Scripts, and SaveData. Scripts contains various .vbs files, including gui.vbs.
I start with gui.html. I click a button which takes me to load.html. load.html uses scripts from Scripts\gui.vbs. One of the functions loads a database, and to do so I provide the location of the database: C:\Documents and Settings\Lauren\Desktop\STKGui\SaveData\SaveData.accdb Of course I want to use a relative file path instead of a fixed path. My initial attempt to load the database failed; it was trying to load from C:\Documents and Settings\Lauren\Desktop\SaveData\SaveData.accdb. So to troubleshoot I printed out the current working directory; much to my chagrin it was C:\Documents and Settings\Lauren\Desktop
I don't understand why my desktop is my current working directory. Shouldn't it be where the file is running from? I figured it would be either C:\Documents and Settings\Lauren\Desktop\STKGui (the location of load.html) OR C:\Documents and Settings\Lauren\Desktop\STKGui\Scripts (the location of gui.vbs which contains the function that's trying to load the database/printing debug messages of the current working directory).
Can someone explain why the current working directory is what it is, or better yet tell me how to get what I really want, which is the location of the files executing? (I don't care if it's the main STKGui folder or the scripts folder--as long as it's within the application's directory structure I can work with it!)
EDIT (7/14/10 4:02 pm EDT):
Various attempts at printing the current working directory or grabbing files based on what I -thought- was the relative path from my executing script have resulted in my desktop's path instead of the path of the executed script. I stumbled across this link: http://leereid.wordpress.com/2008/03/19/vbscript-current-directory-or-folder/ but none of the solutions are working for me, as I get run-time errors regarding the Wscript object. So while I don't know if any of the solutions on the aforementioned link will produce different results, if someone can help me get at least one of them working so I can find out that may be a step in the right direction.
One of the solutions, reproduced below:
Set oShell = CreateObject("WScript.Shell")
Set ofso = CreateObject("Scripting.FileSystemObject")
oShell.CurrentDirectory = ofso.GetParentFolderName(Wscript.ScriptFullName)
produces the following error:
Object required: 'Wscript' line: 659 char: 1
with line 659 being:
oShell.CurrentDirectory = ofso.GetParentFolderName(Wscript.ScriptFullName)
For Server-Side:
You should be using Server.MapPath() to get your "working directory". For instance, if you want to get the path to your database file in C:\Documents and Settings\Lauren\Desktop\STKGui\SaveData\SaveData.accdb, your app root being C:\Documents and Settings\Lauren\Desktop\STKGui, you would use Server.MapPath("SaveData\SaveData.accdb").
For Client-Side:
Upon closer examination and digging up some memories, I realized that MapPath is only available from the Server class. Instead, you need to create a file system object like this:
''get fs object
Set objFSO = CreateObject("Scripting.FileSystemObject")
''get actual file using path relative to calling vbs file
Set objFile = objFSO.GetFile("SaveData\SaveData.accdb")
''get path to the database
set sPathToDatabase = objFSO.GetAbsolutePathName(objFile)
In case it helps, here is a great resource for working with the file system in vbScript: http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/filesfolders/files/
This solution was NOT ideal, but what I ended up doing was parsing the url in my browser to get the directory.
guiPath = Mid(location.PathName, 2, len(location.PathName))
Set regExp = New RegExp
regExp.IgnoreCase = False
regExp.Global = True
regExp.Pattern = ".*/"
Set matchCollection = regExp.Execute(guiPath)
Set match = matchCollection(0)
guiPath = match.value
regExp.Pattern = "%20"
guiPath = regExp.Replace(guiPath, " ")
systemsDBPath = guiPath & "SaveData\SaveData.accdb"
Like I said, less than ideal. May not even work once I'm working with the application this will be running in. But I couldn't find a better way.

IsFile, IsDirectory Test Windows

I'm trying to convert a program from Linux to use on Windows, and it calls test -f, or test -d on Linux. I need it to do the same thing on Windows. Is there a built-in command, or another program I can use to do the same thing?
I'm programming using FreeBASIC (horrible, but it's what I got).
EDIT: An external program is the best option here. I've looked at the API, and it's not good.
Never heard of FreeBasic before but looking at the help there's a DIR command that supports using fbDirectory as one of the attribute patterns to filter for.
And looking slightly further down on that page I just saw that they have a sample for checking if the objects found are files or directories. Just look here, look at the second example on that page.
Not sure what exactly those test commands do, but if you want to test if a specific object is a directory you should be able to call Dir("exactname", fbDirectory, something) I'd thought. And then you could test for a file by putting a Not in somewhere (assuming that FreeBasic supports that).
Edit: To make your own tool, here's a sample that shows a tiny C++ app that could easily be changed to look for directories or not. Look for the FindFirstFile in the sample and shortly after that it checks if it's readonly, which could be changed for FILE_ATTRIBUTE_DIRECTORY.
http://unxutils.sourceforge.net/
you can use test.exe just like under linux
Not sure about FreeBASIC, have you looked into vbscript? You could use the FileSystemObject
Dim fso, msg
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FolderExists(fldr)) Then
'Do Something here
Else
'Do Something
End If
If (fso.FileExists(filespec)) Then
'Do Something here
Else
'Do Something
End If
You can also use Kiwi for FreeBasic in order to check if a path leads to a file or directory. You can find Kiwi on Github (https://github.com/nsiatras/kiwi)
#include once "kiwi\kiwi.bi"
#include once "kiwi\io.bi"
' Declare a new file
Dim myFile as File = File("C:\Users\nsiat\Desktop\Test.txt")
' Check if file exists, is a File or is a Directory
print "File exists: " & myFile.exists()
print "Is file: " & myFile.isFile()
print "Is Directory: " & myFile.isDirectory()

Resources