Visual basic closing a file - file

I'm using Visual basic 2012, and I'm experimenting with manipulating .txt files. I've managed to make a button to create them, but the button I made to delete them always runs into and error, claiming the file is still in use. I've tried to write code to close the file, but no success. The closest I've gotten was when I tried
FileStream.Close("C:\Testfile")
But I get an error saying that It needs to be linked to an object. I don't have the faintest idea what it mean by object, and I don't have any other ideas
Can someone tell me what I need to do to fix this, or alternatively, another solution

You must make sure that the code you have for creating the file, closes that file as well after the job is done:
Dim sw As StreamWriter = New StreamWriter("C:\Testfile")
' write to the file here, like:
sw.Write("...")
' ...etc, and at the end of the job, close the file:
sw.Close()
To actually delete a file from the file system, use:
File.Delete("C:\Testfile")

I suspect the problem that you are having could be because the file is still open when you are trying to delete it.
Add your file manipulation code inside a Using block as explained in this MSDN article. By using this technique you will not have to remember to close files yourself as it will happen automatically once you have left the Using block.
Dim filePath As String = "hello.txt"
Using openedFile As FileStream = File.Open(filePath, FileMode.OpenOrCreate)
'File is OPEN
Dim bytes() As Byte = Encoding.ASCII.GetBytes("Hello World")
openedFile.Write(bytes, 0, bytes.Length)
End Using
'File is CLOSED and can be deleted
File.Delete(filePath)
You can also use this technique for any other objects that implement IDisposable such as StreamReader and StreamWriter.

Related

File extension Script task and Error handling

I've literally no experience in VB script or C#. I've created this SSIS package using some online tutorial which server my purpose but I've to fine-tune it to fit my requirements.
Current Scenario:
I'm trying to run an SSIS package which has a for-each loop container which imports the files with *.txt extension in a directory as the file names are not constant. This for-each loop container is followed by some other SQL tasks.
The package is executed successfully even when there are no files in the directory (May be I did something wrong while creating the container and data flow tasks, file system tasks). This is causing the SQL script at the end of the for-each loop container to execute successfully which is resulting in wrong data.
Requirement:
The package should fail if there is no file in directory. I've to implement a script before for-each loop container but not sure how to do it. Any leads would be appreciated!
I did something like this but not sure how to search wrt extension rather than file name:
Public Sub Main()
'
' Add your code here
'
Dim fileName As String
fileName = "filename.txt"
If System.IO.File.Exists(fileName) Then
Dts.Variables("User::bolFileExists").Value = True
Else
Dts.Variables("User::bolFileExists").Value = False
End If
Dts.TaskResult = ScriptResults.Success
End Sub
You should use System.IO.Directory.GetFiles() function.
If System.IO.Directory.GetFiles(<your path goes here>, "*.txt", SearchOption.AllDirectories).Length = 0 Then
Dts.Variables("User::bolFileExists").Value = False
Else
Dts.Variables("User::bolFileExists").Value = True
End If
Below would be my suggestion, I did the same in one of my requirements using event handling section that the underlying DFT is not run, then the script in event handler page would raise error. The point to be noted is that the DFT runs atleast once if there is any file in directory, raising error if it not runs would be simple rather than writing a complex script
Thanks,
Srinivas

SSIS Macro not able to open Excel

I have following code to open the excel file.
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkBook = xlApp.Workbooks.Open("c:\\Temp\\MyExcel.xls"); // absolute path needed
Thread.Sleep(30000);
xlApp.Quit();
If I place this code in any code file using website or window application it runs fine, it also opens my excel file which automatically runs macros and complete the logic in it.
But when I put the same code in SSIS and try to run the code, it doesn't work.
Can anyone please guide me further in this? It is getting critical.
Thanks in advance.

How to resolve FileStream "Error #3013: File or directory is in use" in Action Script 3?

I know this type of questions are already asked by many users but that didn't resolved my problem.
I am using a FileStream to write some content in a file and following are the codes which i am using to do this :
var fs:FileStream = new FileStream ();
fs.open( f , FileMode.WRITE ); // f is contains the file path
fs.writeBytes ( fzf.content ); // fzf is a FZipFile which contains some content
fs.close ();
But problem is that initially if I am writing a file then that is working perfectly but without closing the application if I am trying to write another file then that is showing the error "File or directory is in use" at line fs.open,so I don't know where i am doing wrong as i am calling the close() after writing the write method.
If anybody can find where I am doing wrong or how to resolve this problem please help me to solve.
You are trying to save the files one after another, right ? If so this error comes up because the files are not closing fast enough before you try to write the next one. You should use the openAsync() instead of open() and listen for the Event.CLOSE event on your Filestream (it is only triggered in the asynchronous mode). When it is triggered you can write the next file:
var fs:FileStream = new FileStream ();
fs.addEventListener(Event.CLOSE, onFileClosed);
fs.openAsync( f , FileMode.WRITE ); // f is contains the file path
fs.writeBytes ( fzf.content ); // fzf is a FZipFile which contains some content
fs.close ();
private function onFileClosed(e:Event):void
{
// The file was closed succesfully, it is now safe to write the next one
}

Can't get rid of a deleted Settings reference in DataSet.Designer.vb

I had a connection string to a MS Access DB file, Foo.accdb, defined and used in my project. It was defined as a connection string Setting in the Settings section of my project properties. The program referenced the connection string setting and everything worked fine.
Then I decided to replace Foo.accdb with two different DB files, A.accdb and B.accdb each of which would be used under different circumstances. I added connection strings for them in Settings and removed the Setting definition for Foo.accdb connection string.
The name of my application is Foo and the name of the Foo.accdb connection string was FooConnectionString.
But now when I build the program both in debugger and for release I get the following error message:
'FooConnectionString' is not a member of 'Foo.My.MySettings'.
The offending reference, in file FooDataSet.Designer.vb, is:
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
Private Sub InitConnection()
Me._connection = New Global.System.Data.OleDb.OleDbConnection
Me._connection.ConnectionString = Global.Foo.My.MySettings.Default.FooConnectionString
End Sub
What is going on here? FooConnectionString is not in any other file in the project directory nor in the My Project subdir. I completely got rid of it in my code and in my project properties yet it persists in FooDataSet.Designer.vb (whatever that is).
While researching this on the web I saw a recommendation to select the FooDataSet.xsd file, right click it and execute the "Run Custom Tool" option. I did this and it appears to rebuild FooDataSet.Designer.vb (the time stamp changes) but the problem persists.
I also tried removing the offending reference by manually editing FooDataSet.Designer.vb but that gave me some other error message.
Why is this old reference staying around and what can I do about it?
This is a standalone app. I'm using VS2008 Standard Ed., VB.Net 3.5
Thanks.
Open the FooDataSet XSD file in a text editor. Right click on dataset in the solution explorer and select "Open With..." and the select XML (text) Editor or open it outside the solution.
Look for the <Connections> tag near the top of the file. Remove the line that looks like this
<Connection AppSettingsObjectName="Settings" AppSettingsPropertyName="FooConnectionString" ConnectionStringObject="" IsAppSettingsProperty="true" Modifier="Assembly" Name="FooConnectionString(Settings)" ...

Silverlight IsolatedStorage: Delete not working, Truncate leaving blank space

I'm using IsloatedStorage in a Silverlight app to log information on the client, and I added a function to clear the log file. However, I have had problems with the two approaches I tried:
Approach one: use
IsolatedStorageFile.DeleteFile("log.log");
Result: This fails and returns an "[IsolatedStorage_DeleteFile]" error (No other info). The function works fine on test files, e.g. DeleteFile("test.txt"), but refuses to delete the log. I though that perhaps the log is being used, and tried to close it with
IsolatedStorageFileStream.close()
But this returns a different error "[IsolatedStorage_StoreNotOpen]". I know it is open as the previous line of code successfully logs a message.
Approach Two: Reopen the log file using the Truncate file mode,
_storageFileStream = new IsolatedStorageFileStream(logfilename, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite, _storageFile);
According to MSDN, Truncate "Specifies that the operating system should open an existing file. Once opened, the file should be truncated so that its size is zero bytes." However, it opens my log file and fills it with blank space! The filesize is left identical, the next log message is appended to the end of all of the space.
I've found a way to do this, not by closing but by disposing:
IsolatedStreamWriter.Dispose();
IsolatedStorageFile.DeleteFile("log.log");
IsolatedStorageFileStream = new IsolatedStorageFileStream(logfilename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, _storageFile);
Didn't get the 'truncate' approach to work, but no need now.

Resources