FILESTREAM - Reading documents stored in the File System using SQLFileStream - c#

I saved Filestream documents in the NTFS. Each time I attempt to access them using the block below, I get the 'Parameter Is Not Valid' error message on the Image.FromStream line. Would this have anything to do with the stored files in the FS folder? Or are my parameters missing something?
Is there a way to view the files in the folder to verify they are well formed?
private static Image LoadPhotoImage(string filePath, byte[] txnToken)
{
Image photo;
try
{
using (SqlFileStream sfs =
new SqlFileStream(filePath, txnToken, FileAccess.Read))
{
photo = Image.FromStream(sfs,false);
sfs.Close();
}
return photo;
}
catch (ArgumentException ae)
{
System.Diagnostics.Debug.WriteLine(ae.Message);
return null;
}
}

You can't use SqlFileStream for this purpose, per the MSDN Documentation:
"The SqlFileStream class is used to work with varbinary(max) data stored with the FILESTREAM attribute in a SQL Server 2008 database."
Just use Image.FromFile to load the image.

Related

Create a valid PDF from a web request

I'm trying to create a scanning solution. Basically the user is physically scanning a page. The printer is making an API call, passing in the binary data of the scan in the body.
I'm trying to save this as a PDF on the server, but when I go to open the file, i'm getting an error "There is an error while reading a stream".
var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
var bodyText = bodyStream.ReadToEnd();
string pathToFiles = HttpContext.Current.Server.MapPath("~\\UploadedFiles\\WriteLines.pdf");
try
{
using (StreamWriter outputFile = new StreamWriter(pathToFiles, false))
{
outputFile.WriteLine(bodyText);
}
HttpContext.Current.Response.ContentType = "application/pdf";
}
catch (Exception ex)
{
throw (ex);
}
This is just testing something, and I have permissions etc for writing the file, it's just not creating a valid file.
Any thoughts on what I should use? I have looked into some libraries, but they don't seem to cover what i'm after
StreamReader.ReadToEnd convert bytes to string in particular encoding (UTF8 by default). I don't think this work for PDF.
You need copy bytes directly in the output file :
var bodyStream = HttpContext.Current.Request.InputStream;
bodyStream.Seek(0, SeekOrigin.Begin);
string pathToFiles = HttpContext.Current.Server.MapPath("~\\UploadedFiles\\WriteLines.pdf");
using (FileStream outputFile = File.Create(pathToFiles))
{
bodyStream.CopyTo(outputFile);
}

Uploading files to server - c#

I build a client server application for uploading file from a client folder to server.
My server WebMethod for uploading follows -
[WebMethod]
public string UploadFile(byte[] f, string fileName)
{
// the byte array argument contains the content of the file
// the string argument contains the name and extension
// of the file passed in the byte array
new general().logError("UploadFile " + fileName);
try
{
// instance a memory stream and pass the
// byte array to its constructor
MemoryStream ms = new MemoryStream(f);
FileStream fs = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath
("~/data/") + fileName, FileMode.Create);
// write the memory stream containing the original
// file as a byte array to the filestream
ms.WriteTo(fs);
// clean up
ms.Close();
fs.Close();
fs.Dispose();
new general().logError("After saving the file");
// return OK if we made it this far
return "OK";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
The function that calls this WebMethod follows -
private void uploadIt(string fName)
{
FileStream f = File.OpenRead(fName);
cloudius.cloudius m = new cloudius.cloudius();
using (MemoryStream ms = new MemoryStream())
{
f.CopyTo(ms);
//string[] drive = fName.Split(':');
string[] p = fName.Split('\\');
string b = m.UploadFile(ms.ToArray(), p[p.Length - 1]); //
}
}
When running the aboce code I get the following error -
Client found response content type of 'text/html', but expected 'text/xml'.
Any idea what is causing this error ?
By the looks of things after some research, it looks like it is a form of a error page coming back. Go have a look here as well as here.
Hope this gives you some form of clarification on your problem.
Hey buddy if the main purpose of your method is just to upload a file you can use :
FileUpload fu; // Get the FileUpload object.
using (FileStream fs = File.OpenWrite("file.dat"))
{
fu.PostedFile.InputStream.CopyTo(fs);
fs.Flush();
}
That will be more efficient, as you will be directly streaming the input file to the destination host, without first caching in memory or on disk.

From URL of Video GetThumbnail Using Nreco

I working on a sharepoint project in which i have to upload the videos in the document library as videoset. after creating a video set i have have to upload the video and fetch the thumbnail from the video and upload it. video is uploaded succesfully using
spfile = item.Folder.Files.Add(fuUpload.FileName, fuUpload.PostedFile.InputStream, true);
I am using using Nreco to get thumbnail from the video. However my code works fine on local machine but its giving error "http://mysite/Download/abc/abc.mp4: Server returned 401 Unauthorized (authorization failed) (exit code: 1)" when i am using my application from other pc browsers.
ffMpeg.GetVideoThumbnail(videoPath, ms, 10); the error line.
here is the code i am using
private MemoryStream SaveThumbnail(string videoPath)
{
MemoryStream ms;
try
{
videoPath = "http://mysitehttp/Download/abc/abc.mp4"
ms = new MemoryStream();
SPSecurity.RunWithElevatedPrivileges(delegate() {
var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
ffMpeg.GetVideoThumbnail(videoPath, ms, 10);
});
}
catch(Exception ex)
{
throw ex;
}
return ms;
}
Finally I have managed to solve this. For some reason SharePoint did not allow me to access the file directly from URL using NReco so i tweaked the function like this.
Instead of using file URL as argument i used the file object it self. and copied the stream on server temp folder in virtual directories then i used the file path on the system for NRreco to create the thumbnail. and in the end deleted the file from the server.
private MemoryStream SaveThumbnail(SPFile videoFile)
{
MemoryStream ms;
try
{
//Creating Temp File Path to be used by Nreco
ms = new MemoryStream();
SPSecurity.RunWithElevatedPrivileges(delegate() {
string destinationFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + videoFile.Name);
//Copying the content the content of the file at temp loaction from stream
using (FileStream fileStream = File.Create(destinationFile))
{
Stream lStream = videoFile.OpenBinaryStream();
byte[] contents = new byte[lStream.Length];
lStream.Read(contents, 0, (int)lStream.Length);
lStream.Close();
// Use write method to write to the file specified above
fileStream.Write(contents, 0, contents.Length);
fileStream.Close();
}
var ffMpeg = new NReco.VideoConverter.FFMpegConverter();
ffMpeg.GetVideoThumbnail(destinationFile, ms, 10);
System.IO.File.Delete(destinationFile);
});
}
catch(Exception ex)
{
throw ex;
}
return ms;
}
Someone might save some time from my answer. if anyone has a better solution let me know please.

C# Save image without using Dialog

I am having trouble saving a user uploaded image to my "logos" file when the user presses "Save Team" on my form.
For you to get a taster of what the application does I have provided a screenshot here, upon pressing add team all the text box data is written to a text file and I want the image to automatically save into a predefined folder "logos", however I get the GDI++ error whenever I press save.
After reading through a few old threads on the web, I found that it could be caused by a few things such as file permissions, file size, the files name or even an open stream.
Below is the code I am currently using to save out my file which prompts the error:
private void btnAddTeam_Click(object sender, EventArgs e)
{
//VALIDATION FOR TEXT FILE AND OTHER STUFF HERE...
//SAVE THE IMAGE FILE
string filePath = picTeamLogo.ImageLocation;
Image tempImage = Image.FromFile(filePath);
tempImage.Save(#"../logos/");
}
If you are viewing the screenshot, please do not get confused by "arsenal.png" I am aware that that is not the full file path, its conversion is handled in another method, as only the filename is required to be written to the text file.
If anybody has any ideas on where I am going wrong then please point me in the right direction, vague errors such as the GDI one I just received are such a headache!
Alex.
Try this method
public void storeFile(FileUpload File, string dirName)
{
if (!Directory.Exists(MapPath("~/uploads/" + dirName)))
{
Directory.CreateDirectory(MapPath("~/uploads/" + dirName));
}
string saveLocation = MapPath("~/uploads/" + dirName + "/" + Path.GetFileName(File.FileName));
File.SaveAs(saveLocation);
}
that's because you have not specified the file name for save function !
take a look at this :
string filePath = picTeamLogo.ImageLocation;
FileInfo fi = new FileInfo(filePath);
Image tempImage = Image.FromFile(fi.FullName);
tempImage.Save(#"../logo/" + fi.Name);
now it works properly
See this earlier post of mine for similar issue...
A Generic error occurred in GDI+ in Bitmap.Save method
The stream remains locked - you can use memory stream as a temp location then save.
When either a Bitmap object or an Image object is constructed from a
file, the file remains locked for the lifetime of the object. As a
result, you cannot change an image and save it back to the same file
where it originated.
http://support.microsoft.com/?id=814675
string outputFileName = "...";
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
tempImage.Save(memory, ImageFormat.Jpeg);
// memory.ToStream(fs) // I think the same
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
Or alternative is loading image via MemoryStream into the image - so the stream doesn't get locked in the first place...

The action can't be completed because the file is open in IIS Worker Process

I am uploading a image for a user & saving it on a specified location. The code is working fine in normal scenario i.e. user selects a image & save it, it works.
Challenge occurs when user selects a image( probably wrong image due to mistake) & don't save it, but again selects a new image & then saves it.
This scenario gives me the error :
"The process cannot access the file because it is being used by another process."
When I try to delete image from the location at the time of error, file can't be deleted with message:
"The action can't be completed because the file is open in IIS Worker Process
Close the file and try again."
Code is like this:
try
{
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
msf = new MemoryStream();
bytes=FileUpload1.FileBytes;
msf.Write(bytes, 0, bytes.Length);
using (FileStream stream = new FileStream(folder + "/" + filename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
//converting any graphic file type to jpeg format
Image img = Image.FromStream(msf);
img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
msf.WriteTo(stream);
IsuploadSuccess = true;
img.Dispose();
}
}
catch
{
IsuploadSuccess = false;
}
finally
{
if (msf != null)
{
msf.Close();
msf.Dispose();
}
}
I have tried adding "FileAccess.ReadWrite" & "FileShare.ReadWrite" in file stream, but doesn't work either with all options in File stream.
Please help...
Instead of getting solution of problem, I finally change approach to get rid to source of challenge. I change file name with UserID (unique) appended with CurrentDateTime converted to string & store it to temp folder until user save the change. This forms a different file each time for the challenge scenario. After save each file in temp folder created by the user (preceded by unique userid) is deleted & last changes are saved to respective directory.
I had this problem and took me few hours to figure it out.
I my case the Bitmap new(path) had locked the file. I had to dispose of it before exiting the using block.
However it is the method by which I debugged it is important.
My approach in pinpointing the source of the problem was to open the folder where the image was saved and tracing the code line by line. After each line I deleted the file and did Ctrl+Z to put it back. If it gave an error when I tried to delete it, then that is the line that locked it. So I got to that line within 5 min.
using (MemoryStream memoryStream = new())
{
if (System.IO.File.Exists(path))
{
using(Bitmap bitmap = new(path)) <-- this solved it
{
ImageConverter imageConverter = new();
bitmap.Save(memoryStream, ImageFormat.Bmp);
bytes = memoryStream.ToArray();
}
}
}

Categories