ImageList imageList = new ImageList();
if (folder != null && System.IO.Directory.Exists(folder))
{
try
{
string[] arrImageName=new string[1000];
int Count = 0;
string CutName;
DirectoryInfo dir = new DirectoryInfo(#folder);
foreach (FileInfo file in dir.GetFiles())
{
try
{
imageList.ImageSize = new Size(140, 140);
imageList.ColorDepth = ColorDepth.Depth32Bit;
Image img1 = Image.FromFile(file.FullName);
CutName = file.FullName;
CutName = CutName.Replace(folder, "");
CutName = CutName.Replace("\\", "");
arrImageName[Count] = CutName;
imageList.Images.Add(FormatImage(imageList.ImageSize.Width, img1));
Count = Count + 1;
}
catch
{
Console.WriteLine("This is not an image file");
}
}
for (int j = 0; j < imageList.Images.Count; j++)
{
this.ListView1.Items.Add((j + 1) + "/" + imageList.Images.Count + " " + "\r\n" + arrImageName[j]);
this.ListView1.Items[j].ImageIndex = j;
}
this.ListView1.View = View.LargeIcon;
this.ListView1.LargeImageList = imageList;
//import(folder);
}
catch (Exception ex)
{
}
}
You cant do this
Image img1 = Image.FromFile(file.FullName);
because a PDF is not an image format and is not understood by .NET.
Here is a thread on how to convert the PDF to an image using a 3rd party library
Related
string fname = "";
string filename = "";
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string filess = files[i].FileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = DateTime.Now.ToString("ddMMMyyyyhhmissmmm") + testfiles[testfiles.Length - 1];
filename = filename + Path.GetFileName(fname);
}
else
{//some code here
fname = DateTime.Now.ToString("ddMMMyyyyhhmissmmm") + file.FileName;
filename = filename + Path.GetFileName(fname);
}
string replacestr = System.Text.RegularExpressions.Regex.Replace(filename, "[^a-zA-Z0-9_]+", " ");
fname = replacestr;
fname = replacestr;
fname = fname.Replace(" ", "").Replace(",", "").Trim();
fname = fname + "";
fname = fname + ".png";
filename = fname;
fname = Path.Combine(context.Server.MapPath("../admin/img/product_images/"), fname);
file.SaveAs(fname);
//some code here
}
}
//Do This Work watermarkenter image description here
Bitmap bmp = new Bitmap(file.InputStream);
Graphics graphicsobj = Graphics.FromImage(bmp);
Brush brush = new SolidBrush(Color.FromArgb(80, 255, 255, 255));
Point postionWaterMark = new Point((enter image description herebmp.Width / 6), (bmp.Height / 2));
graphicsobj.DrawString("Daphnisys Technology", new System.Drawing.Font("Arial", 30, FontStyle.Bold, GraphicsUnit.Pixel), brush, postionWaterMark);
Image img = (Image)bmp;
string filepath = HttpContext.Current.Server.MapPath("../admin/img/product_images/") + filename;
//image.Save(filepath);
img.Save(filepath, System.Drawing.Imaging.ImageFormat.Png);
graphicsobj.Dispose();
System.IndexOutOfRangeException: Index was outside the bounds of the array.
How to solve this error ?
Can anyone know this ?
Below my coding... when execute it produce the error that
System.IndexOutOfRangeException Index was outside the bounds of the array
, only if tried to process this csv file :
Instead I don't have error if tried to process this csv file :
Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateBinaryReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
result.Tables[0].TableName.ToString();
string csvData = "";
int row_no = 0;
int ind = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
csvData += result.Tables[ind].Rows[row_no][i].ToString() + "|";
}
row_no++;
csvData += "\n";
}
keys = GetUniqueKey(12).ToUpper();
output = System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv");
StreamWriter csv = new StreamWriter(#output, false);
csv.Write(csvData);
csv.Close();
csv.Dispose();
string toCheck;
using (var fs = new FileStream(output, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.Default))
{
toCheck = sr.ReadToEnd();
if (toCheck.Contains("ColumnAAA") == false)
{
////Start add new column
int posNewColumn = 2;
string[] CSVDump = File.ReadAllLines(output);
List<List<string>> CSV = CSVDump.Select(x => x.Split('|').ToList()).ToList();
for (int i = 0; i < CSV.Count; i++)
{
if (CSV[i].Count > posNewColumn)
{
CSV[i].Insert(posNewColumn, i == 0 ? "ColumnAAA" : "ColumnAAA");
}
else
{
CSV[i].Add(i == 0 ? "ColumnAAA" : "ColumnAAA");
}
}
File.WriteAllLines(output, CSV.Select(x => string.Join("|", x)));
sr.Close();
////End add new column
}
}
Edit #01
The problem is in this line of code-behind.
The code print correctly the number of rows, but I have error when try print and Split the number of columns :
lines = File.ReadAllLines(System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv"));
rows = lines.Count();
columns = lines[23].Split('|').Count();
Response.Write("Number of rows/columns = " + rows.ToString() + "/" + columns.ToString());
Response.End();
Try this :
lines = File.ReadAllLines(System.Web.HttpContext.Current.Server.MapPath("/public/" + keys.ToString() + ".csv"));
rows = lines.Count();
int i = 0;
foreach (string line in lines)
{
string[] parts = line.Split('|');
foreach (string part in parts)
{
columns = parts.Count();
}
i++;
}
Response.Write("Number of rows/columns = " + rows.ToString() + "/" + columns.ToString());
Response.End();
The first saved file name on the hard disk is: 201701311645---0 then 201701311645---1 then 201701311645---20 then 201701311645---21 then 201701311645---40 and 201701311645---41
But i want it to be saved as: 201701311645---0 then 201701311645---1 then 201701311645---2 then 201701311645---3 then 201701311645---4 and 201701311645---5
In the top i added a counter variable
private int countFilesNames = 0;
Then in a dowork event i also reset the counter to 0 once so if i start the backgroundworker over again it will start from 0.
private void bgwDownloader_DoWork(object sender, DoWorkEventArgs e)
{
Int32 fileNr = 0;
countFilesNames = 0;
if (this.SupportsProgress) { calculateFilesSize(); }
if (!Directory.Exists(this.LocalDirectory)) { Directory.CreateDirectory(this.LocalDirectory); }
while (fileNr < this.Files.Count && !bgwDownloader.CancellationPending)
{
m_fileNr = fileNr;
downloadFile(fileNr);
if (bgwDownloader.CancellationPending)
{
fireEventFromBgw(Event.DeletingFilesAfterCancel);
cleanUpFiles(this.DeleteCompletedFilesAfterCancel ? 0 : m_fileNr, this.DeleteCompletedFilesAfterCancel ? m_fileNr + 1 : 1);
}
else
{
fileNr += 1;
}
}
}
Then in the downloadFile method
private void downloadFile(Int32 fileNr)
{
FileStream writer = null;
m_currentFileSize = 0;
fireEventFromBgw(Event.FileDownloadAttempting);
FileInfo file = this.Files[fileNr];
Int64 size = 0;
Byte[] readBytes = new Byte[this.PackageSize];
Int32 currentPackageSize;
System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch();
Int32 readings = 0;
Exception exc = null;
try
{
writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
"---" + countFilesNames + ".png", System.IO.FileMode.Create);
}
catch(Exception err)
{
string ggg = err.ToString();
}
HttpWebRequest webReq;
HttpWebResponse webResp = null;
try
{
webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path);
webResp = (HttpWebResponse)webReq.GetResponse();
size = webResp.ContentLength;
}
catch (Exception ex) { exc = ex; }
m_currentFileSize = size;
fireEventFromBgw(Event.FileDownloadStarted);
if (exc != null)
{
bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc);
}
else
{
m_currentFileProgress = 0;
while (m_currentFileProgress < size && !bgwDownloader.CancellationPending)
{
while (this.IsPaused) { System.Threading.Thread.Sleep(100); }
speedTimer.Start();
currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize);
m_currentFileProgress += currentPackageSize;
m_totalProgress += currentPackageSize;
fireEventFromBgw(Event.ProgressChanged);
writer.Write(readBytes, 0, currentPackageSize);
readings += 1;
if (readings >= this.StopWatchCyclesAmount)
{
m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000 / (speedTimer.ElapsedMilliseconds + 1));
speedTimer.Reset();
readings = 0;
}
}
speedTimer.Stop();
writer.Close();
webResp.Close();
if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); }
}
fireEventFromBgw(Event.FileDownloadStopped);
countFilesNames += 1;
}
I build the file name:
writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
"---" + countFilesNames + ".png", System.IO.FileMode.Create);
The move the counter forward by 1:
countFilesNames += 1;
But i'm getting other files names then i wanted.
Maybe there is a better way to give the files names some identity ? The problem is that if i will not give the files names some identity it will overwrite the files all the time. The files names are the same the content is not so i need to give each file another name.
Why don't you just increment the counter only when a file is written (since the variable doesn't look like it is accessed elsewhere) and not below:
writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
"---" + countFilesNames++ + ".png", System.IO.FileMode.Create);
This way the counter won't be incremented on errors.
I am writing on my pdf-word converter and I just received a really strange exception witch makes no sens to me.
Error:PdfiumViewer.PdfException:{"Unsupported security scheme"}
Its the first time that such a exception appears. but I have to be honest that I never tried to convert more then 3-4 files from pdf to word and right now I am doing more then 100 files.
Here is my code I am sry if its too long but I simply do not know on which line the error occurs
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
string path = #"C:\Users\chnikos\Desktop\Test\Batch1\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
var doc = application.Documents.Add();
using (var document = PdfiumViewer.PdfDocument.Load(file))
{
int pagecount = document.PageCount;
for (int index = 0; index < pagecount; index++)
{
var image = document.Render(index, 200, 200, true);
image.Save(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\Test\Batch1\output" + index.ToString("000") + ".png");
}
string getFileName = file.Substring(file.LastIndexOf("\\"));
string getFileWithoutExtras = Regex.Replace(getFileName, #"\\", "");
string getFileWihtoutExtension = Regex.Replace(getFileWithoutExtras, #".pdf", "");
string fileName = #"C:\Users\chnikos\Desktop\Test\Batch1\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
.....
}
doc.PageSetup.TopMargin = 28.29f;
doc.PageSetup.LeftMargin = 28.29f;
doc.PageSetup.RightMargin = 30.29f;
doc.PageSetup.BottomMargin = 28.29f;
application.ActiveDocument.SaveAs(fileName, WdSaveFormat.wdFormatDocument);
doc.Close();
string imagePath = #"C:\Users\chnikos\Desktop\Test\Batch1\";
Array.ForEach(Directory.GetFiles(imagePath, "*.png"), delegate(string deletePath) { File.Delete(deletePath); });
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
}
}
In thst code i have us two database tabele and fetch data in datatable then write all the data in the csv files with help of stream writer then add both the file in a folder and download in a zip form but sometimes its shows an error The process cannot access the file 'xxxxx.zip' because it is being used by another process.
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
//Work Detail
blExportToExcel obj = new blExportToExcel();
System.Data.DataTable dtTechSanc = blDbFunction.GetTechSanc(ddlAgency.SelectedValue.ToString(), ddlDivision.SelectedValue.ToString(), ddlDistrict.SelectedValue.ToString(), ddlMC.SelectedValue.ToString(), ddlScheme.SelectedValue.ToString(), ddlUserType.SelectedValue.ToString(), ddlWorkType.SelectedValue.ToString(), ddlWorkNature.SelectedValue.ToString(), ddlWorkStatus.SelectedValue.ToString(), ((prpSessionData)(Session["sUserInfo"])).UId);
dtTechSanc.Columns["Id"].ColumnName = "WorkCode";
dtTechSanc.Columns["TSId"].ColumnName = "Id";
string filenamezip = "ZipFile\\TechSancRevision_" + DateTime.Now.ToString().Replace(":", "-").Replace("/", "-") + ".zip";
string strPathAndQuery = HttpContext.Current.Request.PhysicalApplicationPath;
string paths = strPathAndQuery + filenamezip;
ZipFile z = ZipFile.Create(paths);
z.BeginUpdate();
if (dtTechSanc.Rows.Count > 0)
{
string tmpPath = Server.MapPath("FileTemplates");
string tmpFileName = "TechSancRevision.csv";
tmpPath = #"" + tmpPath.Replace("/", "\\").Replace("\\Department", "") + "\\" + tmpFileName;
StreamWriter sw = new StreamWriter(tmpPath, false);
int columnCount = dtTechSanc.Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(dtTechSanc.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtTechSanc.Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
z.Add(tmpPath, tmpFileName);
z.CommitUpdate();
}
//Fund Allocation
System.Data.DataTable dtFA = blDbFunction.GetFundAllocationTS(ddlAgency.SelectedValue.ToString(), ddlDivision.SelectedValue.ToString(), ddlDistrict.SelectedValue.ToString(), ddlMC.SelectedValue.ToString(), ddlScheme.SelectedValue.ToString(), ddlUserType.SelectedValue.ToString(), ddlWorkType.SelectedValue.ToString(), ddlWorkNature.SelectedValue.ToString(), ddlWorkStatus.SelectedValue.ToString(), ((prpSessionData)(Session["sUserInfo"])).UId);
if (dtFA.Rows.Count > 0)
{
z.BeginUpdate();
string tmpPath = Server.MapPath("FileTemplates");
string tmpFileName = "FundsAllocationRevision.csv";
tmpPath = #"" + tmpPath.Replace("/", "\\").Replace("\\Department", "") + "\\" + tmpFileName;
dtFA.Columns["FAId"].ColumnName = "Id";
dtFA.Columns["WorkId"].ColumnName = "WorkCode";
StreamWriter sw = new StreamWriter(tmpPath, false);
int columnCount = dtFA.Columns.Count;
for (int i = 0; i < columnCount; i++)
{
sw.Write(dtFA.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtFA.Rows)
{
for (int i = 0; i < columnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
z.Add(tmpPath, tmpFileName);
z.CommitUpdate();
z.Close();
}
System.IO.FileInfo file = new System.IO.FileInfo(paths);
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + Path.GetFileName(paths));
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);/// error shows here
Response.End();
}
}
I am not sure this will help you or not but i am transmitting zip using below code , please try it. It works perfectly and in use from past 2 years.
Response.ContentType = "application/zip";
Response.AppendHeader("Content-Disposition", "attachment; filename=Test.zip")
Response.TransmitFile(#"C:\Test.zip");
Response.Flush();
// Prevents any other content from being sent to the browser
Response.SuppressContent = true;
// Directs the thread to finish, bypassing additional processing
HttpContext.Current.ApplicationInstance.CompleteRequest();