473,669 Members | 2,471 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

File writes in a loop

I need to write data to a file in a loop. I get a "file already in
use" error on the second loop. The problem is, I don't know the name
of the file until I'm in the loop. How can I keep a file open for
writing in a loop?

while ((data = log.ReadLine()) != null)
{
string date = data.Substring( 0, 10);
FileStream fileOut = new FileStream(dir + date + name,
FileMode.OpenOr Create, FileAccess.Writ e);

fileOut.Write(E ncoding.UTF8.Ge tBytes(data), 0, data.Length);
fileOut.Flush() ;
}
Jun 27 '08 #1
10 2465
while ((data = log.ReadLine()) != null)
{
string date = data.Substring( 0, 10);
using (FileStream fileOut = new FileStream(dir + date + name,
FileMode.OpenOr Create, FileAccess.Writ e))
{
byte[] bytes = Encoding.UTF8.G etBytes(data);
fileOut.Write(b ytes, 0, bytes.Length);
}
<Ad*********@gm ail.comwrote in message
news:bc******** *************** ***********@l64 g2000hse.google groups.com...
>I need to write data to a file in a loop. I get a "file already in
use" error on the second loop. The problem is, I don't know the name
of the file until I'm in the loop. How can I keep a file open for
writing in a loop?

while ((data = log.ReadLine()) != null)
{
string date = data.Substring( 0, 10);
FileStream fileOut = new FileStream(dir + date + name,
FileMode.OpenOr Create, FileAccess.Writ e);

fileOut.Write(E ncoding.UTF8.Ge tBytes(data), 0, data.Length);
fileOut.Flush() ;
}

Jun 27 '08 #2
On May 16, 3:35 pm, AdemusPr...@gma il.com wrote:
I need to write data to a file in a loop. I get a "file already in
use" error on the second loop. The problem is, I don't know the name
of the file until I'm in the loop. How can I keep a file open for
writing in a loop?

while ((data = log.ReadLine()) != null)
{
string date = data.Substring( 0, 10);
FileStream fileOut = new FileStream(dir + date + name,
FileMode.OpenOr Create, FileAccess.Writ e);

fileOut.Write(E ncoding.UTF8.Ge tBytes(data), 0, data.Length);
fileOut.Flush() ;

}
are you going have multiple files open in the loop?if yes and you
dont want to close them then you could
use a a hashtable and use dir + date + name as the key and the
filestream as the object.
Jun 27 '08 #3
On May 16, 3:35*pm, AdemusPr...@gma il.com wrote:
I need to write data to a file in a loop. I get a "file already in
use" error on the second loop. The problem is, I don't know the name
of the file until I'm in the loop. How can I keep a file open for
writing in a loop?

while ((data = log.ReadLine()) != null)
{
string date = data.Substring( 0, 10);
FileStream fileOut = new FileStream(dir + date + name,
FileMode.OpenOr Create, FileAccess.Writ e);

fileOut.Write(E ncoding.UTF8.Ge tBytes(data), 0, data.Length);
fileOut.Flush() ;

}
Your question is cryptic, so I am just guessing here but maybe you
need a:

fileOut.Close() ;

after the flush?

And maybe even a:

fileOut.Dispose ();
Jun 27 '08 #4
Thank you for the reply.

This code will close, dispose and reopen the file on each loop.
Therefore, after each loop there is only one record in the output file
which is a last write.
Jun 27 '08 #5
Not sure which part is cryptic. I need to open the file for writing
and keep it open in a loop.

I can close and/or dispose the object but I want to keep the file open
for writing instead of making roundtrip opens/closes each time. Plus,
i would have to advance the cursor to the end of the file each time I
open it, which could be big.
Jun 27 '08 #6
<Ad*********@gm ail.comwrote:
I need to write data to a file in a loop. I get a "file already in
use" error on the second loop.
You aren't closing the file. After calling Flush, call Close.

Eq.
Jun 27 '08 #7
On Fri, 16 May 2008 13:08:07 -0700, <Ad*********@gm ail.comwrote:
Not sure which part is cryptic. I need to open the file for writing
and keep it open in a loop.
You keep saying "the file", but then you also imply that you may have more
than one file.
I can close and/or dispose the object but I want to keep the file open
for writing instead of making roundtrip opens/closes each time.
If you have more than one file you might open in the loop, then you need
to keep track of all the files you've opened. You've already been
provided suggestions for doing that.

If you only have one file, then I recommend putting the FileStream
variable outside the loop, initialized to null, and creating the
FileStream instance only if the variable is null. If it's not null, just
use the current value of the variable.
Plus,
i would have to advance the cursor to the end of the file each time I
open it, which could be big.
The size of the file make absolutely no difference with respect to
seeking. You could in fact close and reopen the file each iteration of
the loop, seeking to the end of the file before writing each time (or just
use FileMode.Append instead of OpenOrCreate). The only real performance
overhead would be the act of opening and closing the file; the seeking
isn't a problem at all.

But the fact is, there's not any need to reopen the file each time through
the loop. Whether you have more than one file or not, there is a
perfectly good solution that doesn't involve reopening the file with each
iteration of the loop.

Pete
Jun 27 '08 #8
On Fri, 16 May 2008 13:08:07 -0700 (PDT), Ad*********@gma il.com wrote:
>Not sure which part is cryptic. I need to open the file for writing
and keep it open in a loop.

I can close and/or dispose the object but I want to keep the file open
for writing instead of making roundtrip opens/closes each time. Plus,
i would have to advance the cursor to the end of the file each time I
open it, which could be big.
You need to close the file after flushing it. If you need to add to
the file in a subsequent iteration, I would first check to see if the
file exists yet or not with the File.Exists method.

If if does not exist, open the file for create or open. If it does,
open it for append.
Jun 27 '08 #9
Joe,

In my idea do you give the best solution

(This in fact to the OP to try this first).

Cor

"Joe Cool" <jo*****@home.n etschreef in bericht
news:ph******** *************** *********@4ax.c om...
On Fri, 16 May 2008 13:08:07 -0700 (PDT), Ad*********@gma il.com wrote:
>>Not sure which part is cryptic. I need to open the file for writing
and keep it open in a loop.

I can close and/or dispose the object but I want to keep the file open
for writing instead of making roundtrip opens/closes each time. Plus,
i would have to advance the cursor to the end of the file each time I
open it, which could be big.

You need to close the file after flushing it. If you need to add to
the file in a subsequent iteration, I would first check to see if the
file exists yet or not with the File.Exists method.

If if does not exist, open the file for create or open. If it does,
open it for append.
Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2678
by: Chuck | last post by:
Problem: to rename a file sent to a PDF writer A macro opens a report in print mode the printer is a pdf writer The report name is: "Directory.pdf" The desired name is: "Directory " & (format(Date(),"yymmdd")) & ",pdf" So that the file name becomes: "Directory 050126.pdf" I have tried the NAME {oldfilename} AS {newfilename} as an event procedure In: On Close and On Deactivate.
4
1510
by: phantom | last post by:
Hi All. I am having a problem writing to a file. I can successfully open the file and write the contents using fprintf, however if the writing is not done for a while in the process the file write returns a status -1. To elaborate here is the code segment main (... , ...) {
7
2250
by: Naren | last post by:
Hello All, Can any one help me in this file read problem. #include <stdio.h> int main() {
26
2990
by: Michel Rouzic | last post by:
I have a binary file used to store the values of variables in order to use them again. I easily know whether the file exists or not, but the problem is, in case the program has been earlier interupted before it could write the variables to the file, the file is gonna be empty, and then it's gonna load a load of crap into variables, which i want to avoid. That file is always 36 bytes big (it contains 4 double-precision floats and one...
5
1579
by: Protoman | last post by:
Here's a program I wrote that calcs the fibonacci numbers and writes them to a file, from 1-50. It prints to the screen just fine, but it only prints the last number, Fib(50) to the file. Code: //FIB.hpp #pragma once
3
7113
by: Avi | last post by:
I need to create a text file that has the data from the 10 tables in the database. The number of fields in the tables exceeds 255 and so I cannot make a new table with all the fields and then export it into a text file. Is there any s/w out there I could use? I am not much of a programmer but I heard I could use VBA to get this done. Any help with the code will be appreciated. Thanks
2
1935
by: Suman | last post by:
Happy Friday everyone!!! I am working on a windows service and a C# application and needed some help with certain functionality. Please read through my issue below. Thanks! I have a windows service which writes into a log file periodically (text file). I want to create a windows form application, which, upon invocation should continuously display the contents of the log file. Even the newly made entries into the log file while the...
2
4191
by: Bonzol | last post by:
vb.net 2003 Windows application We have a Client/Server system set up by communicating through a TCPClient object. The server loops continuously using a tcplistener device and each time a client object attempts a connection, a new instance of a Client object is created (in the server's clients hashtable). The client object on the server (the client solution itself has same communication setup only with the code in the main form) handles...
0
1710
grassh0pp3r
by: grassh0pp3r | last post by:
Hello, I'm trying to make a very simple comments page on my site using PHP and am having problems somewhere. I am very new to PHP. I was able to create one that works with comments appended, but I want the latest comment to be on top, and that's where I'm running into trouble. Since I know very little about PHP, I thought I was clever in what I came up with. I think it can work if I get the coding right. Let me know if my logic is wrong. I'm...
0
8465
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8383
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8894
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8587
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7407
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6210
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4384
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2792
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1787
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.