I am using the below method to extract an image from a uploaded video and placing the image into a folder.
private string GeneratePreviewImageMP4(string FileName, HttpPostedFile file, string ProperPath)
{
string inputfile = System.IO.Path.Combine(Server.MapPath(ProperPath), file.FileName);
string ext = System.IO.Path.GetExtension(FileName);
string thumbpath = AppDomain.CurrentDomain.BaseDirectory + "Reports\\TrainingLibrary\\Videothumbnails\\";
string thumbname = thumbpath + FileName.Replace(ext, "") + ".jpg";
string thumbargs = "-i " + inputfile + " -ss 00:00:25.435 -qscale:v 2 -vframes 1 " + thumbname;
Process thumbproc = new Process();
thumbproc.StartInfo.FileName = "C:\\FFMPEG\\Bin\\ffmpeg.exe";
thumbproc.StartInfo.Arguments = thumbargs;
thumbproc.StartInfo.UseShellExecute = false;
thumbproc.StartInfo.CreateNoWindow = false;
thumbproc.StartInfo.RedirectStandardOutput = false;
try
{
thumbproc.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
thumbproc.WaitForExit();
thumbproc.Close();
return FileName.Replace(ext, ".jpg");
}
The issue, is that once the image is extracted, I get locked out of the folder. No body has admin rights to that folder. We have to restart the Server just to restore access to that folder.
This is only at certain times, most of the time it works great, but one out of ten times there will be an issue.
Anyone now why this is happening? Does it play the video to extract the image, but does not stop the video?
Try calling Dispose on thumbproc after you are done using it
Try using a lock:
lock (_aStaticObject)
{
//All the code above
}
A word of warning, it can be bad for performance to use a lock inside of a http request (thou shall not mess with thy server's threads), which is why this type of thing belongs in a job.
Related
Getting error file corrupt error when downloading large files using Ionic.zip in c#. When user extracts that file file corrupt is being shown. When i am doing same with smaller no of files than it is working fine. Even it is not giving any error while creating zip files. I am creating zip file of existing pdf files which are added in one zip files. There may be 5 files or may 1000 files of minimum 10 MB each.
I have tried with threshold and all other options provided on google, but didn't find any solutions.
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Level9;
//zip.AddDirectoryByName("Files");
for (int i = 0; i < dt.Rows.Count; i++)
{
filePath = Convert.ToString(dt.Rows[i]["filePath"]);
fileIds.Add(Convert.ToInt32(dt.Rows[i]["fileid"]));
string fileFullName = Convert.ToString(dt.Rows[i]["fileName"]);
string fName = Convert.ToString(dt.Rows[i]["fileName"]).Split('_')[1];
//ExceptionLogging c1 = new ExceptionLogging("filePath = " + filePath + " fileFullName = " + fileFullName +
// " fName = " + fName);
//c1.ErrorLog(HttpContext.Current.ApplicationInstance.Server.MapPath("~/Logs/"));
if (!fileNamesList.Contains(fileFullName.Split('_')[0]))
{
//ExceptionLogging c2 = new ExceptionLogging("In if condition -- filePath = " + filePath);
//c2.ErrorLog(HttpContext.Current.ApplicationInstance.Server.MapPath("~/Logs/"));
zip.AddFile(filePath, "Files");
fileNamesList.Add(fileFullName.Split('_')[0]);
}
else
{
filePath = filePath.Substring(0, filePath.Length - 4) + "_" + fName;
//filePath = filePath.Split('.')[0] + "_" + fName;
zip.AddFile(filePath, "Files");
fileNamesList.Add(fileFullName);
//ExceptionLogging c3 = new ExceptionLogging("In else condition -- filePath = " + filePath + " fileFullName = " + fileFullName);
//c3.ErrorLog(HttpContext.Current.ApplicationInstance.Server.MapPath("~/Logs/"));
}
//zip.AddFile(filePath, "Files");
}
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("ZipFile-{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
//Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
I should be able to download large files inside zip.
My explanation needs more space than a comment:
On x32 platforms the usable ram limit for .Net is holding the program to compress files in larger sizes. Try switching to x64 temporarily and that might fix your problem.
I also suggest research about LOH (Large Object Heap) which knowing it will come in handy for you in future dealing with these kind of scenarios:
An article about LOH
I am putting together a training site for my company and we need to extract an image from each mp4 video we upload. I have searched lots and decided to try FFMPEG.
Here is what I have so far. I'm not getting errors, but no image in the specified folder.
Any help would be appreciated.
string inputfile = Server.MapPath("/Report/TrainingLibrary/Material/Videos/RMSIMAILSignature.mp4");
//string withouttext;
string thumbpath;
string thumbname;
string thumbargs;
//string thumbre;
thumbpath = AppDomain.CurrentDomain.BaseDirectory + "Reports\\ TrainingLibrary\\Material\\Videos\\";
thumbname = thumbpath + "Image" + "%d" + ".jpg";
thumbargs = "-i " + inputfile + " -vframes 1 -ss 00:00:07 -s 150x150 " + thumbname;
Process thumbproc = new Process();
thumbproc = new Process();
thumbproc.StartInfo.FileName = "C:\\FFMPEG\\Bin\\ffmpeg.exe";
thumbproc.StartInfo.Arguments = thumbargs;
thumbproc.StartInfo.UseShellExecute = false;
thumbproc.StartInfo.CreateNoWindow = false;
thumbproc.StartInfo.RedirectStandardOutput = false;
try
{
thumbproc.Start();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
thumbproc.WaitForExit();
thumbproc.Close();
The process cannot access the file because it is being used by another process
private void DeleteReport()
{
int invid = Convert.ToInt32(Session["InvId"]);
string FileName = invid + "_Report" + ".pdf";
string path1 = Server.MapPath("~/Report/" + FileName);
if (File.Exists(path1))
{
File.Delete(path1);
}
}
The error tells you, that the file is used and can't be deleted. So nothing wrong. As you did not formulate a
real question, lets try to help you in following way.
I guess that only your program is using the report, so good possible, you block the report
somewhere else.
E.g., the following code
string path = "C:\\Temp\\test.txt";
FileStream file = File.Open(path, FileMode.OpenOrCreate);
if (File.Exists(path))
File.Delete(path);
raises the same error. It does not necessarily mean that the process is another process.
What you can do is for example, for testing purpose, install SysInternal
http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx and add following code around your
File.Delete statement. Then you will see, what process uses the file:
try
{
File.Delete(path);
}
catch (Exception)
{
using (Process tool = new Process())
{
tool.StartInfo.FileName = #"C:\Program Files (x86)\SysinternalsSuite\handle.exe"; //Your path
tool.StartInfo.Arguments = path + " /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = #"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach (Match match in Regex.Matches(outputTool, matchPattern))
{
Process p = Process.GetProcessById(int.Parse(match.Value));
MessageBox.Show(p.ProcessName); // OR LOG IT
}
}
throw;
}
Credit for handle.exe call to https://stackoverflow.com/a/1263609/2707156
I am converting a website from 1.1 framework to 4.0. The website has functionality to Generate Pdf of the content entered in TextEditor. this website has used "HTMLDoc Software" to convert content to pdf using the below code:
string url, pdfFile, exeFile;
string response = "";
url = GetWebUrl() + "/PDFSpeechDetails.aspx?ArticleId=" + ValueOfQueryString;
pdfFile = HttpContext.Current.Request.PhysicalApplicationPath + "pdfs\\articles\\" + ValueOfQueryString + ".pdf";
exeFile = HttpContext.Current.Request.PhysicalApplicationPath + "html2pdf\\htmldoc.exe";
response = gPDF.ShowPDF(url, pdfFile, exeFile);
and ShowPDF Method is:
public string ShowPDF(string url, string pdfFile, string exeFile)
{
try
{
Process p = new Process();
p.StartInfo.FileName = exeFile;
pdfFile = "\"" + pdfFile + "\"";
string args = " --webpage -f " + pdfFile + " " + url;
p.StartInfo.Arguments = args;
p.Start();
p.WaitForExit();
return "1";
}
catch (Exception ex)
{
return (ex.ToString());
}
}
What the above code is doing:(as the previous developer used)
I have placed a folder named HTML2PDf has an exe file. i am just passing it to argument and running this exe file.
This code is working fine on my local machine as well as on server(I took remote of the server and checked there.), but when i tried to generate the PDF from Outer world means using website's domain name, it does not work. I am not getting any clue why it is not working.
please help me how can i make it working on website.
Can someone tell me what is going to happen in this code when an error is encountered? Ideally it should continue the foreach statement until it gets to the last record, but I suspect it's stopping in the middle of the operation because when I check the number of files moved it's off by 225. If it is in fact stopping because of an error, what can I do to make it continue the loop?
I'm creating a new upload manager for our software and need to clean the old files up. There are about 715 orphaned files equaling around 750 MB after a year and a half of use because the original developers didn't write the code to correctly overwrite old files when a new one was uploaded. They also saved the files in a single directory. I can't stand that so I'm moving all of the files into a structure - Vessel Name - ServiceRequesetID - files uploaded for that service. I'm also giving the users a gridview to view and delete files they no longer need as they work the service.
protected void Button1_Click(object sender, EventArgs e)
{
GridViewRow[] rowArray = new GridViewRow[gv_Files.Rows.Count];
gv_Files.Rows.CopyTo(rowArray, 0);
int i = -1;
foreach(GridViewRow row in rowArray)
{
i++;
string _serviceRequestID = ((Label)gv_Files.Rows[row.RowIndex].FindControl("lbl_SRID")).Text;
string _vesselName = ((Label)gv_Files.Rows[row.RowIndex].FindControl("lbl_VesselID")).Text;
string _uploadDIR = Server.MapPath("uploadedFiles");
string _vesselDIR = Server.MapPath("uploadedFiles" + "\\" + _vesselName);
string _fileName = ((Label)gv_Files.Rows[row.RowIndex].FindControl("lbl_FileName")).Text;
DirectoryInfo dInfo = new DirectoryInfo(_uploadDIR);
DirectoryInfo dVessel = new DirectoryInfo(_vesselDIR);
DirectoryInfo dSRID = new DirectoryInfo(_serviceRequestID);
dInfo.CreateSubdirectory(_vesselName);
dVessel.CreateSubdirectory(_serviceRequestID);
string _originalFile = _uploadDIR + "\\" + _fileName;
string _fileFullPath = Path.Combine(Server.MapPath("uploadedFiles/" + _vesselName + "/" + _serviceRequestID + "/"), _fileName);
FileInfo NewFile = new FileInfo(_fileFullPath);
string _fileUploadPath = _vesselName + "/" + _serviceRequestID + "/" + _fileName;
string sourceFile = _originalFile;
FileInfo _source = new FileInfo(sourceFile);
string destinationFile = _fileFullPath;
try
{
{
File.Move(sourceFile, destinationFile);
movefiles.InsertNewUploadPath(Convert.ToDecimal(_serviceRequestID), 1, _fileUploadPath);
}
}
catch (Exception ex)
{
CreateLogFiles Err = new CreateLogFiles();
Err.ErrorLog(Server.MapPath("Logs/ErrorLog"), ex.Message);
}
}
_utility.MessageBox("Completed processing files.");
}
As long as the error encountered occurs within the try catch clause, the code will continue executing within the foreach loop. However, if the error occurs outside of the try catch, the function will exit and throw an error. How many files does your error log report??