IIS Process Not Letting Go Of Files? - c#

I have written a web app that has to save a few files. I have developed this app in C# using Visual Web Developer 2010 Express. The program executes flawlessly in VWD but when I deploy it to the server it runs into problems. One problem in particular is that the files being saved are held onto by some process and I can't access them or delete them when I need to. I believe I am properly closing the file streams. Here is an example of one such save:
string[] lines = MessagesTextbox.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
string messagesFileLocation = currDir + "\\" + reportDir + "\\" + messagesFile;
FileStream fs2 = File.Open(messagesFileLocation, FileMode.Create, FileAccess.Write);
using (StreamWriter sw = new StreamWriter(fs2))
{
sw.WriteLine("<Messages>");
foreach (string message in lines)
{
if (!message.Equals(""))
{
sw.WriteLine("\t<message>" + message + "</message>");
}
}
sw.WriteLine("</Messages>");
}
fs2.Close();
The problem is also occurring when I use HtmlAgilityPack to save the rendered HTML to a file.
The only difference between my development environment and the server is that on the server my app runs under IIS. Can anyone think of a reason why this problem might occur using IIS when it doesn't occur ever in my development environment? The person who administers the server thinks it has to be my code but, like I said, it has been running for several weeks on my own machine without any of these problems.
Any suggestions are appreciated.
Regards.

Your FileStream fs2 will not be closed if an Exception is thrown. You must close it in a finally block, which you get for free if you wrap it in its own using.
Everything that implements IDisposable should be wrapped in a using block (or otherwise disposed for some advanced cases) as a matter of good coding practice. There are edge cases to be sure where that does not matter, but it is a solid habit to always ensure that IDisposable.Dispose() is called as soon as an object that implements the interface is no longer required.

Related

Application Cannot Acces File even though I can copy it using Explorer

An internal application in our company requires files aa, bb ... zz in folder X to be read upon startup. When I (as someone with FullControl access to folder X) launch the app, all goes fine. When any of my colleagues (who only have Read access to folder X) launch the app, they get an "Access denied to file aa ... " exception.
The files are being read by the following routine
public static void readFromBinaryFile(this QIHasFileIo xThis, string xFilePath)
{
if (!System.IO.File.Exists(xFilePath))
throw new System.Exception("File to read " + xFilePath + " does not exist ... ");
if (xThis == null)
throw new NullReferenceException("xThis cannot be null, as it is a readonly reference ... ");
using (BinaryReader xReader = new BinaryReader(new FileStream(xFilePath, FileMode.Open, FileAccess.Read)))
xThis.readObject(xReader);
}
i.e. I am specifying the Read mode, which should in turn require only Read access to the folder. When my colleagues go to folder X in Explorer, then can copy the aa, bb, ... files to their Desktops, which means they DO have Read access to the files.
So I am intrigued. This weird behaviour started with changes to the data server a couple days ago. The most notable changes were that 1/ my colleagues stopped having admin rights on the data server 2/ some GPO's might have been messed up (it happenned before in the company). The IT department is baffled as well, so I have no clue how to proceed.
Any hint is much appreciated,
Daniel
Edit: An already deleted post proposed using FileShare.ReadWrite. I am grateful to the author for the comment, however the file is guaranteed not to have a write-lock on it. Hence, the why File.copy works but File.OpenRead prompts access denied? thread is not relevant here.
You need to add FileShare.ReadWrite to the parameters passed to the FileStream constructor.
This prevents the application trying to get an exclusive read lock, which might not be possible under some conditions where a shared read-write lock is possible (such as the file being left open for writing by another process).
I had similar problem while reading a file. The issue was with the level of access for the ActiveDirectory group for the particular group (readers group) of users was not setup correctly.
I am not sure if you are using AD group authentication on the server. I would recommend you to check the type of access and groups your colleagues have. Also, you need to check how your application is currently authenticating the users to access the directory.

c# read write same file more robust way?

I'm developing a progress tracking and monitoring type of an application(c# .net 4.5) A single file both gets written and read from a network location.
I'm having trouble (unresponsive UI / Crashes) reading writing that file in such cases:
if network location is momentarily not responding,
if network location is reached over internet and there is considerable lag,
at startup while client firewall kicks in, it grants delayed access to network resources,
So I'm in need of a more robust way of reading and writing rather than
using (StreamWriter wfile = File.AppendText(path))
{
//...
}
using (StreamReader rfile = new StreamReader(path))
{
//...
}
Async methods seem to conflict reader and writer threads. What is the best practice and your suggestions over this issue? Thanks
You need a service to resolve the issue where the service does the reading and writing of the file. Windows does not properly handle the conflicts. If you don't want to create a service use a database like SQL Server which automatically resolves the conflicts. By the way, SQL Server is a service.

StreamWriter in server file is in use, but in local works

I have a webservices's project. I'm trying to write a log per each method using StreamWriter, in my local machine everything is working fine.
Something like this:
static StreamWriter sw;
try{
if (File.Exists(Directorio + FILE_NAME))
{
sw = File.AppendText(Directorio + FILE_NAME);
}
else
{
sw = File.CreateText(Directorio + FILE_NAME);
sw.WriteLine("---LOG ");
}
sw.WriteLine(Date);
sw.WriteLine(Header);
sw.WriteLine();
sw.Close();//*/
}catch(Exception){}
But when is uploaded to the server sometimes it throws an error that can't write because the file is in use. But I close it every time and I thought that with the try catch should ignore that part and continue with the method, because I don't want to affect the process of each method.
I know that is little information, and I can't reproduce my problem here but hope that someone who had an error like this could give me a hint.
Web servers typically handle multiple requests at once. The occasional error is most likely due to one request trying to log while another request is already logging, and not yet done.
If you wish do use your own logging framework, you will need to coordinate writes to the file.
You could also use one of the exceptional, open-source logging frameworks such as NLog.
This could be due to multiple requests coming to web server and one request trying to write to this log file while other is trying to open. possible fix could be thread synchronization, which is not good as it would significantly degrade the performance of web service. Alternatively I'd recommend using nLog (http://nlog-project.org/), used in several projects without any issues.

Visual Studio - Cannot build a simple project more than once

When I try to build a project twice in successon, i get the following error
Error 2 Unable to copy file "obj\x86\Release\iFileUploader.exe"
to "bin\Release\iFileUploader.exe". The process cannot access the
file 'bin\Release\iFileUploader.exe' because it is being used by another process.
If I close Visual Studio and reopen it, I can compile it again but only once.
I have my projects hosted on a Windows network share. The server runs Windows 2008 R2 and Im on a Windows 7 machine and Ive tried setting everyone full control on the share and the folder permission, to no avail.
Ive even run the Unlocker program and checked the Windows Share & Storage Manager to see if anything is using it and nothing is! I cant delete the file when this happens either until I close VS.
Is there a setting I am missing in Visual Studio?!
UPDATE
Have removed all antivirus/antispam, disabled firewall.. so zero security.
Have disabled "Enable the Visual Studio hosting process"
Visual Studio is some how the colprupt with not releasing the handle
UPDATE
Another thread that has exactly the same problem but from years ago !!
Destroy process-less console windows left by Visual Studio debug sessions
UPDATE
I copied the files locally, and that didnt work. So I created a new project and then copied all the code in to the new project and now its working (with the files stored locally)
check your antivirus program is using it or not.
Alternatively use Process Explorer and find for the string - "iFileUploader.exe" and see who's using it. You can easily get the handle and close it.
Several points:
Check if you don't have a process iFileUploader.exe already running in the Windows Task Manager.
Check that nobody is not running a project that could use iFileUploader.exe.
Christian even if you are have your Stream in a using(){} do not declare a new variable of StreamReader for example do not do this
using(StreamReader streamReade = new StreamReader)
{
..... // if you do you will run into that stream being locked
}
//Declare the StreamReader variable out side of the using and then within the using do something like this.
StreamReader streamReader = null
using(streamReader = new StreamReader()
{
}
Make sure that where you have created an instance of the StreamReader or StreamWriter that you have closed the stream.
For example I would create at the application level a StreamReader / StreamWriter instance and set it to null
Class SomeClass
{
public StreamWriter streamwrtFileToCreate = null;
public FileStream fstreamFileStream = null
public SomeMethod(string FileName, string FilePath)
{
FileStream fstreamFileStream = new FileStream(#FileName + #FilePath, FileMode.Create);
streamwrtFileToCreate = new StreamWriter(fstreamUpdateRpt);
streamwrtUpdateRpt.AutoFlush = true;
}
}
Also it would help if you post the exact example of code that you are using when you create the FileStream Instance
I had this issue in VS 2012 windows 7.
Root cause is Avast Antivirus.
Fix is disable Avast whenever needed to work on C++ console
applications
(or)
->Go to Avast Settings
->Active Protection
->File System Shield (Customize)
->uncheck Scan programs when executing

Windows Service hangs when opening OLEDB-connection to Excel-file

I have a Windows Service that hangs when opening an OLEDB-connection to an Excel-file, like this:
using (var connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ fileName + ";Extended Properties=\"Excel 8.0\""))
{
connection.Open();
// start using the connection
}
This code works fine when running as a console application. When I debug the Windows Service with Visual Studio, I can step into the code until I hit the call to connection.Open(). At that point, the thread hangs. No exception is thrown. Visual Studio remains responsive, until I hit the "Break All" or "Stop Debugging" button. At that point, Visual Studio also hangs. When I kill the process, Visual Studio becomes responsive again.
Does anyone know why this happens and how to solve it?
EDIT: fileName is an absolute path; the file was written by the service itself.
After unsuccessfully trying to do this inside the Windows Service, I extracted the business logic into a separate Console Application, and just call that application from within Windows Service. Seems to work fine.
I do not know why this happens, but have you tried to narrow it down by trying to open the file and simply load it into a byte array - to determine whether the issue is with the file system / permissions / etc... rather than OLE DB? If you can open and load the file into a byte array, but OLE DB still hangs, is the CPU pegged which would indicate that there might be something about the file which OLE DB cannot handle?
If you cannot get this to work with OLE DB, have you considered a 3rd party xls / xlsx library like SpreadsheetGear for .NET? You can see live samples here and download a free trial here.
Disclaimer: I own SpreadsheetGear LLC

Categories

Resources