Writing to file

M

mp

trying the following, calculating some values and writing to a comma delim
file.
the file is getting created but it's always blank
what am i missing?
Sub test()
Dim oCSVFile As System.IO.StreamWriter = Nothing

m_sMoldPartFile = "Filename.txt"

oCSVFile = My.Computer.FileSystem.OpenTextFileWriter(m_sMoldPartFile, True)

For Each blockref As Object In m_ssetProfiles

'now read the profiles, figure out the cut lengths, write to textfile opened
above

GetFormCutListFromProfileBlock(blockref, oCSVFile)

End If

Next

'after looping and writing to file, close it

If Not oCSVFile Is Nothing Then

oCSVFile.Close()

End If

End Sub

'def

Sub GetFormCutListFromProfileBlock(ByVal blockref As AcadBlockReference,
ByVal oCSVFile As System.IO.StreamWriter)

''calculate stuff then write to file

Dim CommaDelimLine As String = sQty & "," & _

sMoldPartName & "," & _

sWidthLiner & "," & _

sLengthLiner & "," & _

m_sMatlLinername & "," & _

m_ssheetwidth & "," & _

m_ssheetthick & "," & _

m_shasgrain & "," & _

sLabeltest

'send composed line to file

AppendToCsvFile2(CommaDelimLine, oCSVFile)
 
F

Family Tree Mike

trying the following, calculating some values and writing to a comma delim
file.
the file is getting created but it's always blank
what am i missing?
Sub test()
Dim oCSVFile As System.IO.StreamWriter = Nothing

m_sMoldPartFile = "Filename.txt"

oCSVFile = My.Computer.FileSystem.OpenTextFileWriter(m_sMoldPartFile, True)

For Each blockref As Object In m_ssetProfiles

'now read the profiles, figure out the cut lengths, write to textfile opened
above

GetFormCutListFromProfileBlock(blockref, oCSVFile)

End If

Next

'after looping and writing to file, close it

If Not oCSVFile Is Nothing Then

oCSVFile.Close()

End If

End Sub

'def

Sub GetFormCutListFromProfileBlock(ByVal blockref As AcadBlockReference,
ByVal oCSVFile As System.IO.StreamWriter)

''calculate stuff then write to file

Dim CommaDelimLine As String = sQty& ","& _

sMoldPartName& ","& _

sWidthLiner& ","& _

sLengthLiner& ","& _

m_sMatlLinername& ","& _

m_ssheetwidth& ","& _

m_ssheetthick& ","& _

m_shasgrain& ","& _

sLabeltest

'send composed line to file

AppendToCsvFile2(CommaDelimLine, oCSVFile)

You didn't provide the definition of AppendToCsvFile2(), but the problem
must be in there. You don't actually write to the file in any lines of
code that you posted.
 
M

mp

sorry
Sub AppendToCsvFile2(ByVal CommaDelimLine As String, ByVal oCSVFile As
System.IO.StreamWriter)

oCSVFile.WriteLine(CommaDelimLine)

End Sub
 
M

mp

You didn't provide the definition of AppendToCsvFile2(), but the problem
sorry for top posting...switching from groups that prefre one or the other,
i get confused
:)

mp said:
sorry
Sub AppendToCsvFile2(ByVal CommaDelimLine As String, ByVal oCSVFile As
System.IO.StreamWriter)

oCSVFile.WriteLine(CommaDelimLine)

End Sub


could it be because of byVal instead of byRef?
I'm testing that now.
 
A

Armin Zingler

Am 18.03.2010 01:12, schrieb mp:
could it be because of byVal instead of byRef?

No. Use ByVal as you don't intend to change the variable content.
(and the content is a reference)

Dim CommaDelimLine As String = sQty & "," & _

sMoldPartName & "," & _

sWidthLiner & "," & _

sLengthLiner & "," & _

m_sMatlLinername & "," & _

m_ssheetwidth & "," & _

m_ssheetthick & "," & _

m_shasgrain & "," & _

sLabeltest

Consider using a Stringbuilder instead. Can be much faster; if that matters
in your case.
sorry
Sub AppendToCsvFile2(ByVal CommaDelimLine As String, ByVal oCSVFile As
System.IO.StreamWriter)

oCSVFile.WriteLine(CommaDelimLine)

End Sub

If this is all the sub does, why not directly call oCSVFile.WriteLine
instead of calling AppendToCsvFile2?

the file is getting created but it's always blank

I didn't find an error. How did you check that it's blank?
My.Computer.FileSystem

This is just the longer way to System.IO.
 
M

mp

mp said:
sorry for top posting...switching from groups that prefre one or the
other, i get confused
:)




could it be because of byVal instead of byRef?
I'm testing that now.

ok I give up,
can't get streamwriter to work
went back to
Sub AppendToCsvFile3(ByVal CommaDelimLine As String, ByVal FileName As
String)

File.AppendAllText(FileName, CommaDelimLine + Environment.NewLine)

End Sub

that finally worked

still wonder what 's wrong with the other way though.

thanks

mark
 
F

Family Tree Mike

ok I give up,
can't get streamwriter to work
went back to
Sub AppendToCsvFile3(ByVal CommaDelimLine As String, ByVal FileName As
String)

File.AppendAllText(FileName, CommaDelimLine + Environment.NewLine)

End Sub

that finally worked

still wonder what 's wrong with the other way though.

thanks

mark

The code seems fine, based on what is posted. Obviously I don't know
what some of these classes yare are using that are app specific.

Try setting a break point in AppendToCsvFile2 where the line is written.
Make sure it is actually called. It looks as if you have an if-then
end if block in your loop. Maybe the condition is never met?
 
M

mp

Armin Zingler said:
Am 18.03.2010 01:12, schrieb mp:

No. Use ByVal as you don't intend to change the variable content.
(and the content is a reference)

snip


Consider using a Stringbuilder instead. Can be much faster; if that
matters
in your case.

I can do that, for now just trying to get the frame working, can optimize
later
If this is all the sub does, why not directly call oCSVFile.WriteLine
instead of calling AppendToCsvFile2?

I did replace that inline just to make sure the problem wasn't passing in
the object as arg
didn't solve the problem though

I didn't find an error. How did you check that it's blank?

by opening it in notepad
This is just the longer way to System.IO.

ok, as a newbie, everything i do, is just look up in help and try and find
how to do, so often i will do stupid way,
thanks to all for their help and advice


for now replacing oCSVFile.WriteLine with
File.AppendAllText(FileName, CommaDelimLine + Environment.NewLine)

works, when i open the file in notepad the data is in there

I don't see a oCSVFile.Save method, just a .Close method...i was assuming
that would save the doc on closing.

the problem must be in my loops somewher
I'm opening the object in one sub, calling another in loop, filling in text
in the file repeatedly, then back in the main sub close the file after all
loops done....somethings' not working there with the System.IO.StreamWriter
but it does work with the File object???????
 
M

mp

The code seems fine, based on what is posted. Obviously I don't know what
some of these classes yare are using that are app specific.

Try setting a break point in AppendToCsvFile2 where the line is written.
Make sure it is actually called. It looks as if you have an if-then end
if block in your loop. Maybe the condition is never met?

a direct replace of File.AppendAlltext works where StreamWriter.WriteLine
fails
so something is going on with creating a streamwriter in one sub
passing it to another in a loop
then closing it in the upper sub
that's all i can think of why one works and the other doesn't
 
M

mp

Armin Zingler said:
Am 18.03.2010 01:12, schrieb mp:

This is just the longer way to System.IO.

I tried replacing My.Computer.FileSystem with System.IO. but didnt' get the
method
OpenTextFileWriter()

???

i think i got that line from this entry in the help files
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("c:\test.txt", True)
file.WriteLine("Here is the first string.")
file.Close()
 
M

mp

Family Tree Mike said:
On 3/17/2010 8:39 PM, mp wrote:> The code seems fine, based on what is
posted. Obviously I don't know what some of these classes yare are using
that are app specific.

Try setting a break point in AppendToCsvFile2 where the line is written.
Make sure it is actually called. It looks as if you have an if-then end
if block in your loop. Maybe the condition is never met?

Whichever way i end up getting the writing to work,
in the end i'm trying to write a csv file that excel can open.
I figured i'd just create a .txt file with comma separated values, then
rename to .csv when done...
is there a more direct method in dotnet?

Thanks for all your help
Mark
 
T

Tom Shelton

trying the following, calculating some values and writing to a comma delim
file.
the file is getting created but it's always blank
what am i missing?
Sub test()
Dim oCSVFile As System.IO.StreamWriter = Nothing

m_sMoldPartFile = "Filename.txt"

oCSVFile = My.Computer.FileSystem.OpenTextFileWriter(m_sMoldPartFile, True)

For Each blockref As Object In m_ssetProfiles

'now read the profiles, figure out the cut lengths, write to textfile opened
above

GetFormCutListFromProfileBlock(blockref, oCSVFile)

End If

Where is the if that goes with the end if? It seems you have not posted all
relavent code here... But, writing to a file with a StreamWriter is easy:

Using sw As New StreamWriter("filename.txt")
sw.WriteLine("Hello!")
End Using


So, if it's comming up blank somewhere, then your logic is probably never
callign the writeline method.
 
A

Armin Zingler

Am 18.03.2010 15:59, schrieb mp:
I tried replacing My.Computer.FileSystem with System.IO. but didnt' get the
method
OpenTextFileWriter()

???

You can only use the existing classes and methods in the
System.IO namespace. Look in the object browser and the docs.
Starting point:
http://msdn.microsoft.com/en-us/library/k3352a4t.aspx


And about your problem: You wrote, you opened it in Notepad. Did you
also look at the file size shown in Windows Explorer? (after pressing F5)
I don't know by heart which character encoding is used by default
with your method; maybe Notepad can't handle it.
 
A

amdrit

You can also add some debugging information in your code to see what is
going on as it is happening.

option explicit
option strict

imports system
imports system.io
imports system.diagnostics

dim debuglevel as integer

public sub ExportData()

dim comadelimline as string = string.empty

debuglevel = 4

try

using sw as new streamwriter(file.combine(rootpath, filename))

sw.autoflush = true

For Each blockref As Object In m_ssetProfiles

commadelimline = GetFormCutListFromProfileBlock(blockref)
sw.writeline(commadelimline);

Trace.WriteLineIf(DebugLevel = 4, string.format("file postion is
currently at {0}", sw.posistion )
'sw.posistion might be sw.basestream.posistion

next blockref

end using
end try

catch (ex as Exception)
'Report and Clean-Up
Trace.WriteLineIf(DebugLevel > 1 , string.format("An error occured
exporting the data. {0} The exception reported is: {1}",
environment.newline, ex.tostring() )
Throw new ApplicationException("Unable to export data",ex)
end catch

end sub

private function GetFormCutListFromProfileBlock(ByVal blockref As
AcadBlockReference) as string

''calculate stuff then write to file
Dim CommaDelimLine As String = string.empty

CommaDelimLine = sQty & ","& _
sMoldPartName & ","& _
sWidthLiner & ","& _
sLengthLiner & ","& _
m_sMatlLinername & ","& _
m_ssheetwidth & ","& _
m_ssheetthick & ","& _
m_shasgrain & ","& _
sLabeltest

Trace.WriteLineIf(DebugLevel = 4, commadelimline)

return CommaDelimLine

end function
 
M

mp

Tom Shelton said:
Where is the if that goes with the end if? It seems you have not posted
all
relavent code here... But, writing to a file with a StreamWriter is easy:

right, just a snip from the middle where the streamwriter calls were

Using sw As New StreamWriter("filename.txt")
sw.WriteLine("Hello!")
End Using


So, if it's comming up blank somewhere, then your logic is probably never
callign the writeline method.

it is getting called, per my other posts to this thread i can replace the
streamwriter call with a call to
File.AppendAllText(FileName, CommaDelimLine + Environment.NewLine)

and it works



I heard you can open a streamwriter, make multiple calls to writeline, then
close after instead of opening/closing with each write as in
File.AppendAllText

so i thought it would be more efficient, but (my theory) due to
creating/opening in one sub then passing the object to another sub in a
loop, then closing in the main sub after the loop is done writing multiple
passes, some reason it's not working.

i could post the whole code but it's a lot of crap around this one little
item of interest
 
M

mp

amdrit said:
You can also add some debugging information in your code to see what is
going on as it is happening.

option explicit
option strict

imports system
imports system.io
imports system.diagnostics

dim debuglevel as integer

public sub ExportData()

dim comadelimline as string = string.empty

debuglevel = 4

try

using sw as new streamwriter(file.combine(rootpath, filename))

sw.autoflush = true

For Each blockref As Object In m_ssetProfiles

commadelimline = GetFormCutListFromProfileBlock(blockref)
sw.writeline(commadelimline);

Trace.WriteLineIf(DebugLevel = 4, string.format("file postion is
currently at {0}", sw.posistion )
'sw.posistion might be sw.basestream.posistion

next blockref

end using
end try

catch (ex as Exception)
'Report and Clean-Up
Trace.WriteLineIf(DebugLevel > 1 , string.format("An error occured
exporting the data. {0} The exception reported is: {1}",
environment.newline, ex.tostring() )
Throw new ApplicationException("Unable to export data",ex)
end catch

end sub

private function GetFormCutListFromProfileBlock(ByVal blockref As
AcadBlockReference) as string

''calculate stuff then write to file
Dim CommaDelimLine As String = string.empty

CommaDelimLine = sQty & ","& _
sMoldPartName & ","& _
sWidthLiner & ","& _
sLengthLiner & ","& _
m_sMatlLinername & ","& _
m_ssheetwidth & ","& _
m_ssheetthick & ","& _
m_shasgrain & ","& _
sLabeltest

Trace.WriteLineIf(DebugLevel = 4, commadelimline)

return CommaDelimLine

end function

well, that's a thought to revise GetFormCutListFromProfileBlock from sub to
function and return the string
in this case it would be a string() since it writes several lines, not just
one.
and i'm thinking for some reason that is the problem that i'm trying to
write in an inside one sub but the streamwriter was created and closed in an
enclosing sub
since File.AppendAllText works, i don't know if there's compelling reason to
get the StreamWriter working, but I'd still like to know what i'm doing
wrong.
guess i'll have to do a small test prog to isolate this problem and make
sure something else in my code isn't hosing it...
i'll stick a try catch in there to to see what's up
Thanks for the ideas
mark
 
T

Tom Shelton

right, just a snip from the middle where the streamwriter calls were



it is getting called, per my other posts to this thread i can replace the
streamwriter call with a call to
File.AppendAllText(FileName, CommaDelimLine + Environment.NewLine)

and it works



I heard you can open a streamwriter, make multiple calls to writeline, then
close after instead of opening/closing with each write as in
File.AppendAllText


Yep. Do it all the time.

Using sw As New StreamWriter("file.txt")
For i As Integer = 0 to 10
sw.WriteLine("Hello!")
Next
End Using
so i thought it would be more efficient, but (my theory) due to
creating/opening in one sub then passing the object to another sub in a
loop, then closing in the main sub after the loop is done writing multiple
passes, some reason it's not working.

Ok. Have you steped through the code? Passing the streamwritter around
should be no hinderance to it's working...
i could post the whole code but it's a lot of crap around this one little
item of interest

I don't want you to post the whole code - but a concise, but working example
that illustrates the issue. See here for what I mean:

http://www.yoda.arachsys.com/csharp/complete.html
 
A

amdrit

I am sure there is no reason to abandon the writeall method, as you say, it
works for you.

I do question why you are thinking you need to create an array of strings
though. The end result is to simply write the data to a files and
WriteLine() simply takes your text and appends a line terminator at the end
so it doesn't matter how many line breaks are in the string itself.

dim myString as string = "test1" & vbcrlf & _
"test2" & vbcrlf & _
"test3" & vbcrlf & _
"test4" & vbcrlf & _
"test5"

return myString

I see it as an advantage to always understand why code doesn't behave as you
expect. Call it lessons learned, but building your undestanding on such
topics serves to expedite future approaches and implementations.
 
T

Tom Shelton

trying the following, calculating some values and writing to a comma delim
file.
the file is getting created but it's always blank
what am i missing?

For kicks - I put a small example together that sort of simulates the basic
structure I see in your code. It works just fine:

Option Explicit On
Option Strict On

Imports System.IO
Imports System.Text

Module Module1
Private rnd As New Random()

Sub Main()
Using sw As New StreamWriter("outfile.txt")

For i As Integer = 0 To 100
WriteSomeStuff(sw)
Next
End Using

Process.Start("outfile.txt")
End Sub

Sub WriteSomeStuff(ByVal sw As StreamWriter)
Dim buffer As New StringBuilder()
Dim nums() As Integer = {rnd.Next(1, 101), rnd.Next(1, 101), rnd.Next(1, 101), rnd.Next(1, 101)}
For Each num As Integer In nums
buffer.Append(num).Append(",")
Next
buffer.Length = buffer.Length - 1
AppendToFile(buffer.ToString(), sw)
End Sub

Sub AppendToFile(ByVal line As String, ByVal sw As StreamWriter)
sw.WriteLine(line)
End Sub
End Module

HTH
 
M

mp

amdrit said:
I am sure there is no reason to abandon the writeall method, as you say, it
works for you.

I do question why you are thinking you need to create an array of strings
though. The end result is to simply write the data to a files and
WriteLine() simply takes your text and appends a line terminator at the
end so it doesn't matter how many line breaks are in the string itself.

Good point, i'm just being stupid! that would work fine!
:)
Thanks
Mark
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top