Reading text from a file

Hi,

I am trying to read a text file and pull out each line from the file in a do...loop procedure.

According to the help file, i should use stream reader, however i can't seem to get this to work. Using this, instead of reading a line and waiting, every time i hover over the variable, it changes, so it seems that is is constantly moving on and on.

My text file is just a simple list....

TEST1
TEST2
TEST3

I have corresponding folders created within a subfolder on my C: drive, and what I am trying to achieve is a movedirectory command which will read the first line, and move that folder, move to the next line and move that folder and so on.

This seems like it should be simple, however i cannot get it to read the file properly. Also when i try using EOF with my filename in brackets e.g. EOF(myfile) i get a string conversion error.

This is my code so far....

Imports System.IO

Imports System.Text

Imports System

PublicClass Form1

PrivateSub Button1_Click(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles Button1.Click

Dim MyFileToReadAsString = "c:\Test Folders\testfile.txt"

Dim MyFolderAsString

Dim srAs StreamReader =New StreamReader(MyFileToRead)

sr.ReadLine()

MyFolder = sr.ReadLine

DoUntil sr.EndOfStream()

My.Computer.FileSystem.MoveDirectory("C:\Test Folders\Source Folders\" & MyFolder, "C:\Test Folders\Destination Folders\" & MyFolder.ToString)

MsgBox("Moved " & MyFolder.ToString, MsgBoxStyle.Information, "Folder Moved")

Loop

EndSub

EndClass

Now ok, i am playing around with the do until, so endofstream may well be wrong, however, i need to know what to use in this case to signify the end of the file. As I mentioned EOF is giving off a string conversion error.

I hope someone can help me, as I am EXTREMELY new to VB.NET/2005

TIA

Andy Perry

[3621 byte] By [AndrewPerry] at [2007-12-16]
# 1
Hi,

I'm not very familar with vb but you are reading the first line and then the second one and save this into a variable:

sr.ReadLine()

MyFolder = sr.ReadLine

just leave the first readline and you can read the first line. Also I think if you want to move the folders that are defined in your text you should put that in your loop,too.

rgerbig at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 2
Try this:

Dim MyFileToRead As String = "c:\temp\test.txt"

Dim sr As StreamReader = New StreamReader(MyFileToRead)

Dim MyFolder As String

Do

MyFolder = sr.ReadLine()

My.Computer.FileSystem.MoveDirectory("C:\Test Folders\Source Folders\" & MyFolder, "C:\Test Folders\Destination Folders\" & MyFolder.ToString)

MsgBox("Moved " & MyFolder.ToString, MsgBoxStyle.Information, "Folder Moved")

Loop Until MyFolder Is Nothing

sr.Close()

DannyC at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 3
DannyC's code looks good, although I would suggest one new feature of VS2005 .NET 2 as follows;

Replace ;

Dim sr As StreamReader = New StreamReader(MyFileToRead)

With ;

Using sr As StreamReader = New StreamReader(MyFileToRead)
'Process sr
End Using

GrantCarthew at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 4
Thanks everyone,

I am going to try these out and will let you know how i get on.

Thanks again for your help.

Andy

AndrewPerry at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 5
Thanks for the info Danny,

I have just tried out your suggestion, and i seem to be getting an exception error during debug at the point where it is declaring sr as the streamreader.

The error that is showing is...

Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

I do have Administrator rights on my PC, and all files referred to are on local drive c:

Have you any ideas what I am missing? I have added a line "imports system.security.permissions.fileiopermission" however just clutching at straws here.

Thanks

Andy

Just to add, I have also tried the Using/End Using but this also has the same error on the same line.

AndrewPerry at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 6
Is the Destination folder empty?

Try the following;

My.Computer.FileSystem.MoveDirectory("C:\Test Folders\Source Folders\" & MyFolder, "C:\Test Folders\Destination Folders\" & MyFolder.ToString, True)

GrantCarthew at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 7

Thanks Grant,

I have tried what you suggested, although the error is occuring before i get to the command. However I have but the True at the end. The destination folder did have a folder in.

It still gives the security error.

This is the exact error

....start.....

System.Security.SecurityException was unhandled
Message="Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."
Source="mscorlib"
StackTrace:
at System.Security.CodeAccessSecurityEngine.Check(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 checkFrames, Int32 unrestrictedOverride)

at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)

at System.Security.CodeAccessPermission.Demand()

at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)

at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)

at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)

at System.IO.StreamReader..ctor(String path)

at SAN_Management.Form1.Button1_Click(Object sender, EventArgs e) in \\wwlsan02\users2\PERRY_A\My Documents\Visual Studio\Projects\SAN Management\SAN Management\Form1.vb:line 15

at System.Windows.Forms.Control.OnClick(EventArgs e)

at System.Windows.Forms.Button.OnClick(EventArgs e)

at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)

at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)

at System.Windows.Forms.Control.WndProc(Message& m)

at System.Windows.Forms.ButtonBase.WndProc(Message& m)

at System.Windows.Forms.Button.WndProc(Message& m)

at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)

at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)

at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)

at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)

at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)

at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)

at System.Windows.Forms.Application.Run(ApplicationContext context)

at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()

at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()

at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)

at SAN_Management.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 76

at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)

at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

at System.Threading.ExecutionContext.runTryCode(Object userData)

at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)

at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

at System.Threading.ThreadHelper.ThreadStart()

...end...

Now, I wouldn't even know where to start with all that lot :-)

Thanks

Andy

AndrewPerry at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 8
Andy,

Are you using Windows XP? If so, are you using file encryption?

Just a thought.

Grant.

GrantCarthew at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 9

Hi,

Yes, I am running Windows XP, but as for the file encryption, there is nothing that i have specifically encrypted or should I say, nothing that i am aware of :-)

Would this be specific software that i will have had to install such as PGP? If so, there is definately nothin like that installed.

The text file I am trying to access is local, the only other thing i can think, is that the project itself is saved on a network storage drive on another server, although like i say, the files and folders that the project refers to is all on my local laptop.

Andy

AndrewPerry at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 10
Grant,

I have moved my project over onto my local laptop rather than on the network drive, and all is working fine now, so the issue must have been with the security permissions of the project from the network storage drive.

There was another issue with the code itself, however i have also solved this, it was reading the text file after the Do command, therefore at the end of file it was in the loop when the readline was assigned "nothing" and giving an error :-)

Therefore I moved the MyFolder = sr.ReadLine() command before the Do command, but also moved the one within the loop to the end of the Do Process. I know this is not relevant to the security issue, however, if someone does happen to know even less than I do, then it may help them Big Smile

Thanks for all your help, and everyone else too!!

Andy

AndrewPerry at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...
# 11
It was probably the CAS (Code Access Security) policy causing problems.

Glad you got it sorted Andy.

Regard,

Grant.

GrantCarthew at 2007-9-9 > top of Msdn Tech,Visual Basic,Visual Basic General...