alt text http://img179.imageshack.us/img179/7827/textwriter.jpg
the tf.txt file has 0 bytes and when calling this method several times over the loop I get:
the process cannot access " " because it is being used by another process
Yes, you're not closing the TextWriter. Thus the file handle remains open, so you can't create another one writing to the same file.
Use a using statement:
// Consider using File.CreateText instead, btw
using (TextWriter writer = new StreamWriter(...))
{
...
}
I'm surprised that your file is empty, admittedly... did it throw an exception the first time you called it, e.g. in GetTerms()? That would explain it. You might need a using statement for IndexReader as well, by the way - we can't really tell.
Why is tw.Close commented out? This might be the cause of "is being used by another process" since the file would be held open until closed.
Related
I have a process which have 2 FileStream objects that operates on the same file.
Both objects opens the file using the same method:
file = new FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
Then I write some bytes to them both using write methods, only the last called write is committed while the other is ignored. Write is called using the following code:
fh.file.Write(buffer, 0, count);
buf is equal to "fd" in both calls and count is equal to 2
I call close() for both objects after that. After the program is terminated, the output file only have one of the two "fd"s that should have been written. Why is that happening? I tried calling Flush() on both objects, but it doesn't make a difference.
Note: calls to Write() are done by the same thread.
the final execution order is like this:
open_obj1()
open_obj2()
write_obj1("fd")
write_obj2("fd")
close_obj1()
close_obj2()
It seems like a simple problem, but I can't get where the problem is. Does the both FileStreams reads the file pointer at the same place and then tries to write to the same place because they both seek to the end of file? if so, what's the solution for this if I wanted the exact same execution order?
See Stream.Position; because this property is not shared between your two streams, subsequent writes start at the beginning, thus writing over the previous writes, not unlike switching your text input to overwrite, moving the caret, and typing in new text. Similarly, if you were to write a longer string followed by a shorter one, you would observe the leftover text of the longer string.
Our software needs to produce variable-sized reports, which can easily move past 100 pages. Several of these pages contain large images/Bitmaps.
Is there a reliable way to prevent the overall report from consuming all available memory? Once we have enough pages being generated, the app almost never finishes creating the report without running out of memory. Most of the memory is consumed by Bitmaps that we cannot release. (Attempting to dispose of them before the report is complete causes the report generation to fail.)
John
Have you tried using the cache to disk with ActiveReports?
http://helpcentral.componentone.com/nethelp/AR7Help/OnlineEn/CacheToDiskAndResourceStorage.html
More details here:
http://helpcentral.componentone.com/nethelp/AR7Help/OnlineEn/GrapeCity.ActiveReports.Document.v7~GrapeCity.ActiveReports.Document.SectionDocument~CacheToDisk.html
Set this up prior to running the report. For example:
report.Document.CacheToDisk = true;
report.Run();
I think you could try spliting ur report into smaller chunks ,run them and then merge all the reports into one once all pages have been generated.
One more suggestion in addition to setting CacheToDisk property of ActiverReports to True would be to make use of Image.FromStream instead of Image.FromFile to access the images.
Image.FromFile leaves file handles open, and hence it may result in the Memory Exception.
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (Image original = Image.FromStream(fs))
{
...
}
}
Using an explicit Dispose(), a using() statement or setting the value to null on the bitmap doesn't generally solve the issue with Image.FromFile.
So if you App runs for a time and opens a lot of files consider using Image.FromStream() instead.
Regards,
Mohita
As title says I don't know what's wrong with my code but if (File.Exists) give negative result even if the file is there.
Below is my code
if (File.Exists(ZFileConfig.FileName.Replace(".xml", "_abc.xml")))
Here, ZFileConfig.FileName is E:\\Application\\Application\\bin\\Debug\\resources\\FirstFile.xml
And amazingly ZFileConfig.FileName.Replace(".xml", "_abc.xml") gives me E:\\Application\\Application\\bin\\Debug\\resources\\FirstFile_abc.xml that is what is needed. EVENTHOUGH IF falied to return TRUE.
It looks like your file is actually named abc_RotateFlip.xml.xml.
I can't imagine why any programmer would ever allow hidden file extensions, but your Excel file shows that they are indeed hidden. Turn that off! Choose to know what's going on inside your computer!
You can also use this registry script to change that setting;
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced]
"HideFileExt"=dword:00000000
Please check with FileInfo :
FileInfo fi = new FileInfo(#"_abc.xml");
bool isExists = fi.Exists;
Generally if you are performing a single operation on a file, use the File class. If you are performing multiple operations on the same file, use FileInfo.
The reason to do it this way is because of the security checking done when accessing a file. When you create an instance of FileInfo, the check is only performed once. However, each time you use a static File method the check is performed.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to both Read/Write File in C#
I want to write and read text to and from the same text file. Here is the code
TextWriter notesWriter = new StreamWriter("text.txt");
TextReader notesReader; = new StreamReader("text.txt");
Once the file is open for writing it is being locked and prevents to read from it.
So, some exception is thrown like,
The process cannot access the file 'text.txt' because it is being used by another process.
what is the workaround for this ? thank you.
EDIT:
Suppose, if want to change text in a textbox and save it in a file and read from it when required to set the text in the textbox.
Every time you finish writing you should Close the file, unless you need to write AND read at the same time which is impossible something you should not do because not so safe/hard/useless in most cases with standard text files used to store data.
Try something like
using(TextWriter notesWriter = new StreamWriter("text.txt"))
{
//do write-things here
}
after the closing-braked the Streamwriter will be disposed and you can read the file.
The workaround is not to do it. While technically this can be done, the way you want to do it (by accessing the file using stream semantics) is almost impossible to be correct as, even if you fix the file sharing, it would imply you're reading back the same stuff you wrote in an infinite loop.
You can use a paging based file access metaphor, which again is very unlikely what you want to do.
The most likely option is that you want to write into a different file, a (modified?) copy of the original file, and then swap the copy with the original file.
Sure you can read and write at the same time, but you only need one reference:
Stream l_fileStream = File.Open( "text.txt", FileMode.Open, FileAccess.ReadWrite );
http://msdn.microsoft.com/en-us/library/s67691sb.aspx
Now you can read/write to the file:
StreamReader l_reader = new StreamReader( l_fileStream );
StreamWriter l_writer = new StreamWriter( l_fileStream );
Why would you want to do this? I have no idea. Seems like you'd want to finish one operation before beginning the next, unless you want to get down and dirty in the actual byte array (like an advanced paging system), in which case you may not be quite at the experience level to pull such a thing off.
You don't need to read and write at the same time, considering your edits.
Open the application
Read the file. Put the file's content in the textbox. Close the file
Save the textbox content into the file. Close the file.
As you can see, you never need to read and write at the same time if you close the file in between your uses.
I have a noteapp, two pages:
MainPage.xaml — the creation of notes;
NoteList.xaml — a list of notes.
Notes are saved by means of IsolatedStorage, and appear in NoteList.xaml (listbox), but notes with the same name is not stored, how to fix it?
I need to be able to add notes with the same name (but with different content).
Thanks!
Are you using the note name as the file name? If so... don't do that. Save each file with a unique name. There are myriad ways of doing this. You could use a GUID or a timestamp, or you could append a timestamp to the end of the file name. If you were so inclined you could store all of the notes in a single formatted file-- perhaps XML.
What you need is a way to uniquely identify each note without using:
a. The note's name
b. The note's contents
While using a timestamp might make sense for your application right now (since a user probably cannot create two disparate notes simultaneously), using a timestamp to identify each note could lead to problems down the line if you wanted to implement say... a server side component to your application. What happens if in version 23 of your application (which obviously sells millions in the first months), you decide to allow users to collaborate on notes, and a Note is shared between two instances of your app where they happened to be created at the EXACT same time? You'd have problems.
A reasonable solution to finding a unique identifier for each Note in your application is through the use of the Guid.NewGuid method. You should do this when the user decides to "save" the note (or if your app saves the note the moment it's created, or at some set interval to allow for instant "drafts".
Now that we've sufficiently determined a method of uniquely identifying each Note that your application will allow a user to create, we need to think about how that data should be stored.
A great way to do this is through the use of XmlSerializer, or better yet using the third party library Json.Net. But for the sake of simplicity, I recommend doing something a bit easier.
A simpler method (using good ole' plain text) would be the following:
1: {Note.Name}
2: {Guid.ToString()}
3: {Note.Contents}
4: {Some delimiter}
When you are reading the file from IsolatedStorage, you would read through the file line by line, considering each "chunk" of lines between the start of the file and each {Some delimiter} and the end of the file to be the data for one "Note".
Keep in mind there are some restrictions with this format. Mainly, you have to keep the user from having the last part of their note's contents be equal to the {Some delimiter} (which you are free to arbitrarily define btw). To this end, it may be helpful to use a string of characters the user is not likely to enter, such as "##&&ENDOFNOTE&&##" Regardless of how unlikely it is the user will type that in, you need to check to make sure before you save to IsolatedStorage that the end of the Note does not contain this string, because it will break your file format.
If you want a simple solution that works, use the above method. If you want a good solution that's scalable, use JSON or XML and figure out a file format that makes sense to you. I highly encourage you to look into JSON, it's value reaches so much further than this isolated scenario.
I've had a need to write notes to IsolatedStorage. What I did was to them them to a file.IsolatedStorageFile I write date on which the note was written and then note. From the list box i store them to two arrays. Then before exiting the app, write them to a file.
try
{
using (IsolatedStorageFile storagefile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (storagefile.FileExists("NotesFile"))
{
using (IsolatedStorageFileStream fileStream = storagefile.OpenFile("NotesFile", FileMode.Open, FileAccess.ReadWrite))
{
StreamWriter writer = new StreamWriter(fileStream);
for (int i = 0; i < m_noteCount; i++)
{
//writer.Write(m_arrNoteDate[i].ToShortDateString());
writer.Write(m_arrNoteDate[i].ToString("d", CultureInfo.InvariantCulture));
writer.Write(" ");
writer.Write(m_arrNoteString[i]);
writer.WriteLine("~`");
}
writer.Close();
}
}