Safely read write a .txt file from asp.net - asp.net

I am using a .txt file to log exceptions thrown from various methods in my asp.net (4.0) project. I have a page which reads texts from that file on every 10 minutes. If there are Read and Write attempts at the same time, will it throw any exception? If you have any better technique to handle such problem, please let me know. Currently, i'm using the following code-
Writing to the file
using (StreamWriter Writer = new StreamWriter(LogFilePath, true))
{
Writer.WriteLine(ErrorMsg);
}
Reading from the file
using (FileStream fs=File.OpenRead(LogFilePath))
{
using (StreamReader reader = new StreamReader(fs))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Response.Write(line + "</br>");
}
}
}
Is these approaches are safe?
Thank you.

As people already suggested, the simplest way is to use external libraries, which handle locking of the file.
However, if you still want to use your own code to do that, make sure you're synchronizing access to the file, using lock:
lock(lockObj)
{
using (StreamWriter Writer = new StreamWriter(LogFilePath, true))
{
Writer.WriteLine(ErrorMsg);
}
}
where lockObj is
static object lockObj = new object();

Related

Flex URLRequest

I have some code written by another person. It's uploading a file to a server. I want to post simillar request but without sending a file (my version will copy file of a given name). I can't use method file.Upload(...). So what function I can use?
This is a code of request with file:
var request:URLRequest = new URLRequest(ApiConfig.ApiUrl);
request.method = URLRequestMethod.POST;
request.data = params;
try
{
_fileRef.upload(request);
}
catch(error:Error)
{
Alert.show(error.message);
}
I simply whant to make simillar request, but without uploading file and not using file instance.
I think it's pretty much dumb question but I don't know how to do this.

Returning Multiple Files from MVC Action

So I've got an MVC 3 application that has a couple places where a text file gets generated and returned in an action using:
return File(System.Text.Encoding.UTF8.GetBytes(someString),
"text/plain", "Filename.extension");
and this works fabulously. Now i've got a situation where I'm trying to return a pair of files in a similar fashion. On the view, i have an action link like "Click here to get those 2 files" and i'd like both files to be downloaded much like the single file is downloaded in the above code snippet.
How can I achieve this? Been searching around quite a bit and haven't even seen this question posed anywhere...
Building on Yogendra Singh's idea and using DotNetZip:
var outputStream = new MemoryStream();
using (var zip = new ZipFile())
{
zip.AddEntry("file1.txt", "content1");
zip.AddEntry("file2.txt", "content2");
zip.Save(outputStream);
}
outputStream.Position = 0;
return File(outputStream, "application/zip", "filename.zip");
Update 2019/04/10:
As #Alex pointed out, zipping is supported natively since .NET Framework 4.5, from JitBit and others:
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var file1 = archive.CreateEntry("file1.txt");
using (var streamWriter = new StreamWriter(file1.Open()))
{
streamWriter.Write("content1");
}
var file2 = archive.CreateEntry("file2.txt");
using (var streamWriter = new StreamWriter(file2.Open()))
{
streamWriter.Write("content2");
}
}
return File(memoryStream.ToArray(), "application/zip", "Images.zip")
}
Sorry for bumping an old question but...
Another alternative would be to initiate multiple file downloads using JavaScript, and serve files in two different Action Methods on ASP.NET's side.
You're saying you have a link:
On the view, i have an action link like "Click here to get those 2
files"
So make this link like this:
Click to get 2 files
<script src="download.js"></script>
I'm using download.js script found here but you can find plenty of different other options, see this SO question: starting file download with JavaScript for example
I would advice to create a zip file to include both the files using steps(ALGORITHM):
Create a Zip file and add the desired files into the zip
Return the zip file having all desired files from the action
Java Syntax (Just for understanding)
FileOutputStream fos = new FileOutputStream("downloadFile.zip");
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
zos.putNextEntry(new ZipEntry("Filename1.extension"+));
//write data in FileName1.extension
zos.write(contentBuffer1, 0, len);
zos.putNextEntry(new ZipEntry("Filename2.extension"));
//write data in FileName2.extension
zos.write(contentBuffer2, 0, len);
//write other files.....
zos.close();
Once zip file is created, return the newly created zip file to download.
return File("downloadFile.zip");
.DOT Net Equivalent using DotNetZip
var os = new MemoryStream();
using (var zip = new ZipFile())
{
//write the first file into the zip
zip.AddEntry("file1.txt", "content1");
//write the second file into the zip
zip.AddEntry("file2.txt", "content2");
//write other files.....
zip.Save(os);
}
outputStream.Position = 0;
return File(outputStream, "application/zip", "filename.zip");
Hope this helps!
Look at this SO solution: MVC Streaming Zip File
The advantage of this solution is that it streams the file to the client.
I just implemented this solution a couple of days ago and it worked fantastic.

How do I stream .flv files from SQL database

I want to store .flv files in the database and not in the file system.
This is what I can do right now:
Successfully convert .wmv and .mpeg to .flv with ffmpeg.
Store images in SQL Server and show them on my page with an httphandler.
Same with .avi and .mpeg videos. (It's up to the user's software if he can view it though)
Play .flv files in the browser if the file is located in the file system and not in the database.
What I can't do is:
Stream .flv videos to JW Player directly from the database. (Stored as binary data)
I've searched the internet for two days now but I can't get it to work. It feels as if I'm almost there though. The JW Player opens up and starts to "buffer", but nothing happens.
I know there's no easy answer but if anyone has done this before, or something similar, I'd like to know how you did. I feel I've got too much code to post it all here.
Thanks in advance!
I got it to work but I have no idea as to how efficient it is. Is it better to stream from the file system than from the database in terms of connections, efficency, load etc.
I could use some pointers on this!
I'm using JW Player here, hence "swfobject.js" and "player.swf"
httpHandler:
public class ViewFilm : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
// Check if id was given
if (context.Request.QueryString["id"] != null)
{
string movId = context.Request.QueryString["id"];
// Connect to DB and get the item id
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("GetItem", con))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter sqlParam = cmd.Parameters.Add("#itemId", SqlDbType.Int);
sqlParam.Value = movId;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
dr.Read();
// Add HTTP header stuff: cache, content type and length
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.SetLastModified(DateTime.Now);
context.Response.AppendHeader("Content-Type", "video/x-flv");
context.Response.AppendHeader("Content-Length", ((byte[])dr["data"]).Length.ToString());
context.Response.BinaryWrite((byte[])dr["data"]);
}
}
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
public bool IsReusable
{
get { return false; }
}
}
javascript
The function adds a player to <div id="video1"> and can be called e.g when a user clicks a button.
<script type='text/javascript' src='swfobject.js'></script>
<script type="text/javascript" language="javascript">
function vid() {
var s1 = new SWFObject('player.swf', 'player1', '480', '270', '9');
s1.addParam('allowfullscreen', 'true');
s1.addParam('allowscriptaccess', 'always');
s1.addVariable('file', encodeURIComponent('ViewFilm.ashx?id=10'));
s1.addVariable('type', 'video');
s1.write(document.getElementById("video1"));
}
</script>
Not sure exactly how literally to take "stream directly from the database", but would it work to set the source "file" for the JW Player to "ServeFLV.aspx?id=123", and have ServeFLV.aspx retrieve the bytes from the database, and write them out to the response with no markup?
If you're using SQL Server 2008 you could use varbinary(MAX) FILESTREAM which would allow the files to be managed by the database but still give you access to a FileStream from .NET.

How to rename a file in C#

Consider:
strPath= c:\images\gallery\add.gif
I need to rename this file from add.gif to thumb1.gid, and I should write one command method, whatever the file name. We need to
replace that name with this like below.
string strfilename = **"thumb"**
****Result thum.gif**
strPath= c:\images\gallery\thum.gif **
You have several problems, looking up the value in the XML file, and renaming the file.
To look up the number corresponding to Gallery2 or whatever, I would recommend having a look at Stack Overflow question How to implement a simple XPath lookup which explains how to look up nodes/values in an XML file.
To rename a file in .NET, use something like this:
using System.IO;
FileInfo fi = new FileInfo("c:\\images\\gallery\\add.gif");
if (fi.Exists)
{
fi.MoveTo("c:\\images\\gallery\\thumb3.gif");
}
Of course, you would use string variables instead of string literals for the paths.
That should give you enough information to piece it together and solve your particular lookup-rename problem.
I created a utility method to help encapsulate how to rename a file.
public class FileUtilities
{
public static void RenameFile(string oldFilenameWithPathWithExtension, string newFilenameWithoutPathWithExtension)
{
try
{
string directoryPath = Path.GetDirectoryName(oldFilenameWithPathWithExtension);
if (directoryPath == null)
{
throw new Exception($"Directory not found in given path value:{oldFilenameWithPathWithExtension}");
}
var newFilenameWithPath = Path.Combine(directoryPath, newFilenameWithoutPathWithExtension);
FileInfo fileInfo = new FileInfo(oldFilenameWithPathWithExtension);
fileInfo.MoveTo(newFilenameWithPath);
}
catch (Exception e)
{
//Boiler plate exception handling
Console.WriteLine(e);
throw;
}
}
}
I omitted several other file system checks that could optionally be done, but as #JoelCoehoorn pointed out in a comment on this page, the File System is Volatile, so wrapping it in a try-catch may be all that is necessary.
With that class in your library, now you can simply call:
var fullFilename = #"C:\images\gallery\add.gif";
var newFilename = "Thumb.gif";
FileHelper.RenameFile(fullFilename,newFilename);

Why does Image.FromFile keep a file handle open sometimes?

I am doing a lot of image processing in GDI+ in .NET in an ASP.NET application.
I frequently find that Image.FromFile() is keeping a file handle open.
Why is this? What is the best way to open an image without the file handle being retained.
NB: I'm not doing anything stupid like keeping the Image object lying around - and even if I was I woudlnt expect the file handle to be kept active
I went through the same journey as a few other posters on this thread. Things I noted:
Using Image.FromFile does seem unpredictable on when it releases the file handle. Calling the Image.Dispose() did not release the file handle in all cases.
Using a FileStream and the Image.FromStream method works, and releases the handle on the file if you call Dispose() on the FileStream or wrap the whole thing in a Using {} statement as recommended by Kris. However if you then attempt to save the Image object to a stream, the Image.Save method throws an exception "A generic error occured in GDI+". Presumably something in the Save method wants to know about the originating file.
Steven's approach worked for me. I was able to delete the originating file with the Image object in memory. I was also able to save the Image to both a stream and a file (I needed to do both of these things). I was also able to save to a file with the same name as the originating file, something that is documented as not possible if you use the Image.FromFile method (I find this weird since surely this is the most likely use case, but hey.)
So to summarise, open your Image like this:
Image img = Image.FromStream(new MemoryStream(File.ReadAllBytes(path)));
You are then free to manipulate it (and the originating file) as you see fit.
I have had the same problem and resorted to reading the file using
return Image.FromStream(new MemoryStream(File.ReadAllBytes(fileName)));
Image.FromFile keeps the file handle open until the image is disposed. From the MSDN:
"The file remains locked until the Image is disposed."
Use Image.FromStream, and you won't have the problem.
using(var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
return Image.FromStream(fs);
}
Edit: (a year and a bit later)
The above code is dangerous as it is unpredictable, at some point in time (after closing the filestream) you may get the dreaded "A generic error occurred in GDI+". I would amend it to:
Image tmpImage;
Bitmap returnImage;
using(var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
tmpImage = Image.FromStream(fs);
returnImage = new Bitmap(tmpImage);
tmpImage.Dispose();
}
return returnImage;
Make sure you are Disposing properly.
using (Image.FromFile("path")) {}
The using expression is shorthand for
IDisposable obj;
try { }
finally
{
obj.Dispose();
}
#Rex in the case of Image.Dispose it calls GdipDisposeImage extern / native Win32 call in it's Dispose().
IDisposable is used as a mechanism to free unmanaged resources (Which file handles are)
I also tried all your tips (ReadAllBytes, FileStream=>FromStream=>newBitmap() to make a copy, etc.) and they all worked. However, I wondered, if you could find something shorter, and
using (Image temp = Image.FromFile(path))
{
return new Bitmap(temp);
}
appears to work, too, as it disposes the file handle as well as the original Image-object and creates a new Bitmap-object, that is independent from the original file and therefore can be saved to a stream or file without errors.
I would have to point my finger at the Garbage Collector. Leaving it around is not really the issue if you are at the mercy of Garbage Collection.
This guy had a similar complaint... and he found a workaround of using a FileStream object rather than loading directly from the file.
public static Image LoadImageFromFile(string fileName)
{
Image theImage = null;
fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
{
byte[] img;
img = new byte[fileStream.Length];
fileStream.Read(img, 0, img.Length);
fileStream.Close();
theImage = Image.FromStream(new MemoryStream(img));
img = null;
}
...
It seems like a complete hack...
As mentioned above the Microsoft work around causes a GDI+ error after several images have been loaded. The VB solution for me as mentioned above by Steven is
picTemp.Image = Image.FromStream(New System.IO.MemoryStream(My.Computer.FileSystem.ReadAllBytes(strFl)))
I just encountered the same problem, where I was trying to merge multiple, single-page TIFF files into one multipart TIFF image. I needed to use Image.Save() and 'Image.SaveAdd()`: https://msdn.microsoft.com/en-us/library/windows/desktop/ms533839%28v=vs.85%29.aspx
The solution in my case was to call ".Dispose()" for each of the images, as soon as I was done with them:
' Iterate through each single-page source .tiff file
Dim initialTiff As System.Drawing.Image = Nothing
For Each filePath As String In srcFilePaths
Using fs As System.IO.FileStream = File.Open(filePath, FileMode.Open, FileAccess.Read)
If initialTiff Is Nothing Then
' ... Save 1st page of multi-part .TIFF
initialTiff = Image.FromStream(fs)
encoderParams.Param(0) = New EncoderParameter(Encoder.Compression, EncoderValue.CompressionCCITT4)
encoderParams.Param(1) = New EncoderParameter(Encoder.SaveFlag, EncoderValue.MultiFrame)
initialTiff.Save(outputFilePath, encoderInfo, encoderParams)
Else
' ... Save subsequent pages
Dim newTiff As System.Drawing.Image = Image.FromStream(fs)
encoderParams = New EncoderParameters(2)
encoderParams.Param(0) = New EncoderParameter(Encoder.Compression, EncoderValue.CompressionCCITT4)
encoderParams.Param(1) = New EncoderParameter(Encoder.SaveFlag, EncoderValue.FrameDimensionPage)
initialTiff.SaveAdd(newTiff, encoderParams)
newTiff.Dispose()
End If
End Using
Next
' Make sure to close the file
initialTiff.Dispose()

Resources