Can anyone give me a solution for the below problem since am new to c sharp.
Am having a number of files in directory. Intially i want to load the first file without passing query string, with the first file there should have next file link. Once the next link button is clicked then only have to pass the query string.
how to pass the query string from second file to end of the file,
DirectoryInfo oImageFolderInfo = new DirectoryInfo(this.ImagePath);
FileInfo[] oFileList = oImageFolderInfo.GetFiles("*.*");
string fileName=string.Empty;
if (Request.QueryString["filename"] != null)
{
fileName=(Request.QueryString["filename"]);
}
else
{
fileName = oFileList[0].Name;
}
HtmlImage imag = new HtmlImage();
imag.Src = Url + fileName;
HtmlAnchor nextAnchor = new HtmlAnchor();
nextAnchor.Href=??
nextAnchor.InnerText = "Next>>";
HtmlAnchor prevAnchor = new HtmlAnchor();
prevAnchor.Href=??
How to proceed this same upto reaching the end of the file?
You could use the index of the file for the next and previous button instead of the filename.
DirectoryInfo oImageFolderInfo = new DirectoryInfo(this.ImagePath);
FileInfo[] oFileList = oImageFolderInfo.GetFiles("*.*");
string fileName=string.Empty;
int index = 0;
if (Request.QueryString("i") != null)
index = Request.QueryString("i");
fileName = oFileList[index].Name;
HtmlImage imag = new HtmlImage();
imag.Src = Url + fileName;
if (index > 0)
prevAnchor.Href = String.Format("{0}?i={1}", Url, Index - 1);
if (index < oFileList.Count(
nextAnchor.Href = String.Format("{0}?i={1}", Url, Index + 1);
Related
i am using dropzone to upload multiple files to the server. files will be uploaded to server while file names will be stored in table.
i am trying to add file names in session.
the problem here is that it doesn't add multiple file names inside single session
here is my code :
string imageSessList = context.Session["imageNames"].ToString(); //if i put this line at the begining, then the debugger doesn't even moves to foreach block
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
string strUploadFileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
string strAllowedFileTypes = "***jpg***jpeg***png***gif***bmp***"; //allowed file types
string destFileName = "";
List<string> lstImageNames = new List<string>();
// else upload file
if (!string.IsNullOrEmpty(fileName))
{
if (strAllowedFileTypes.IndexOf("***" + strUploadFileExtension + "***") != -1) //check extension
{
if (context.Request.Files[0].ContentLength < 5 * 1024 * 1024) //check filesize
{
// generate file name
destFileName = Guid.NewGuid().ToString() + "." + strUploadFileExtension;
string destFilePath = HttpContext.Current.Server.MapPath("/resourceContent/") + destFileName;
//Save image names to session
lstImageNames.Add(destFileName);
context.Session["imageNames"] = lstImageNames;
file.SaveAs(destFilePath);
strMessage = "Success " + destFileName;
}
else
{
strMessage = "File Size can't be more than 5 MB.";
}
}
else
{
strMessage = "File type not supported!";
}
}
} // foreach
context.Response.Write(strMessage);
}
here i am able to add only single filename to session, not multiple.
how to store and maintain multiple file names in single session :
context.Session["imageNames"]
you need to get current list from session
List<string> lstImageNames= (List<string>)Session["imageNames"];
if(lstImageNames==null)
lstImageNames = new List<string>(); // create new list in the first time
now add new item to it.
lstImageNames.Add(destFileName);
set back to session
context.Session["imageNames"] = lstImageNames;
I am writing a pdf to word converter which works perfectly fine for me. But I want to be able to convert more than one file.
What happens now is that it read the first file and does the convert process.
public static void PdfToImage()
{
try
{
Application application = null;
application = new Application();
var doc = application.Documents.Add();
string path = #"C:\Users\Test\Desktop\pdfToWord\";
foreach (string file in Directory.EnumerateFiles(path, "*.pdf"))
{
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\pdfToWord\output" + index.ToString("000") + ".png", ImageFormat.Png);
application.Selection.InlineShapes.AddPicture(#"C:\Users\chnikos\Desktop\pdfToWord\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\Test\Desktop\pdfToWord\" + getFileWihtoutExtension;
doc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;
foreach (Microsoft.Office.Interop.Word.InlineShape inline in doc.InlineShapes)
{
if (inline.Height > inline.Width)
{
inline.ScaleWidth = 250;
inline.ScaleHeight = 250;
}
}
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();
}
}
I thought that with my foreach that problem should not occur. And yes there are more than one pdf in this folder
The line
var doc = application.Documents.Add();
is outside the foreach loop. So you only create a single word document for all your *.pdf files.
Move the above line inside the foreach loop to add a new word document for each *.pdf file.
I call the following function to check a specific path and get a list from all the folders located in the given path, for each folder it will check what the folder size is.
This works if i have a file in the folder like this.
Givenfolderpath\Underlying_folder\file.txt
But when there is a subdirectory with a file in it, it will not give me the size of the folder.
Givenfolderpath\Underlying_folder\subdirectory\file.txt
This is my code.
public void ListFolders()
{
dataGridView1.Rows.Clear();
DirectoryInfo di = new DirectoryInfo(Properties.Settings.Default.RevitPath);
DirectoryInfo[] diArr = di.GetDirectories();
foreach (DirectoryInfo dri in diArr)
{
string strCreateTime = dri.LastWriteTime.ToString();
string strCreateDate = dri.LastWriteTime.ToString();
string strCreateSize2 = null;
string strCreateSizeMb = null;
int strCreateSize3;
long strCreateSize1 = GetDirectorySize(Properties.Settings.Default.RevitPath + #"\" + dri);
string strCreateSize = GetSizeReadable(strCreateSize1);
strCreateTime = strCreateTime.Remove(strCreateTime.LastIndexOf(" "));
strCreateDate = strCreateDate.Remove(0,strCreateDate.LastIndexOf(" "));
strCreateSize2 = strCreateSize.Remove(strCreateSize.LastIndexOf(" "));
strCreateSizeMb = strCreateSize.Remove(0, strCreateSize.LastIndexOf(" "));
strCreateSize3 = Convert.ToInt32(strCreateSize2);
if (strCreateSizeMb == " Mb")
{
if (strCreateSize3 >= Properties.Settings.Default.FolderSize)
{
notifyIcon1.ShowBalloonTip(20000, "Attention Required!", dri + " exceed the permissible size " + Properties.Settings.Default.FolderSize + " Mb", System.Windows.Forms.ToolTipIcon.Warning);
}
}
int idx = dataGridView1.Rows.Add();
DataGridViewRow row = dataGridView1.Rows[idx];
row.Cells["User"].Value = dri;
row.Cells["Date"].Value = strCreateTime;
row.Cells["Time"].Value = strCreateDate;
row.Cells["Size"].Value = strCreateSize2;
row.Cells["SizeMB"].Value = strCreateSizeMb;
}
Where does it go wrong?
It will put the data like this.
static long GetDirectorySize(string p)
{
// 1
// Get array of all file names.
string[] a = Directory.GetFiles(p, "*.*");
// 2
// Calculate total bytes of all files in a loop.
long b = 0;
foreach (string name in a)
{
// 3
// Use FileInfo to get length of each file.
FileInfo info = new FileInfo(name);
b += info.Length;
}
// 4
// Return total size
return b;
}
Try replacing the line
DirectoryInfo[] diArr = di.GetDirectories();
with
DirectoryInfo[] diArr = di.GetDirectories("*", SearchOption.AllDirectories);
That should iterate over all directories contained in the given one. See for reference MSDN: DirectoryInfo.GetDirectories Method (String, SearchOption) and MSDN: SearchOption.
I am currently using lucene.net to search the content of files for keyword search. I am able to get the results correctly but I have a scenario where I need to display the keywords found in a particular file.
There are two different files containing "karthik" and "steven", and if I search for "karthik and steven" I am able to get both the files displayed. If I search only for "karthik" and "steven" separately, only the respective files are getting displayed.
When I search for "karthik and steven" simultaneously I get both the files in the result as I am displaying the filename alone, and now I need to display the particular keyword found in that particular file as a record in the listview.
Public bool StartSearch()
{
bool bResult = false;
Searcher objSearcher = new IndexSearcher(mstrIndexLocation);
Analyzer objAnalyzer = new StandardAnalyzer();
try
{
//Perform Search
DateTime dteStart = DateTime.Now;
Query objQuery = QueryParser.Parse(mstrSearchFor, "contents", objAnalyzer);
Hits objHits = objSearcher.Search(objQuery, objFilter);
DateTime dteEnd = DateTime.Now;
mlngTotalTime = (Date.GetTime(dteEnd) - Date.GetTime(dteStart));
mlngNumHitsFound = objHits.Length();
//GeneratePreviewText(objQuery, mstrSearchFor,objHits);
//Generate results - convert to XML
mstrResultsXML = "";
if (mlngNumHitsFound > 0)
{
mstrResultsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Results>";
//Loop through results
for (int i = 0; i < objHits.Length(); i++)
{
try
{
//Get the next result
Document objDocument = objHits.Doc(i);
//Extract the data
string strPath = objDocument.Get("path");
string strFileName = objDocument.Get("name");
if (strPath == null) { strPath = ""; }
string strLastWrite = objDocument.Get("last_write_time");
if (strLastWrite == null)
strLastWrite = "unavailable";
else
{
strLastWrite = DateField.StringToDate(strLastWrite).ToShortDateString();
}
double dblScore = objHits.Score(i) * 100;
string strScore = String.Format("{0:00.00}", dblScore);
//Add results as an XML row
mstrResultsXML += "<Row>";
//mstrResultsXML += "<Sequence>" + (i + 1).ToString() + "</Sequence>";
mstrResultsXML += "<Path>" + strPath + "</Path>";
mstrResultsXML += "<FileName>" + strFileName + "</FileName>";
//mstrResultsXML += "<Score>" + strScore + "%" + "</Score>";
mstrResultsXML += "</Row>";
}
catch
{
break;
}
}
//Finish off XML
mstrResultsXML += "</Results>";
//Build Dataview (to bind to datagrid
DataSet objDS = new DataSet();
StringReader objSR = new StringReader(mstrResultsXML);
objDS.ReadXml(objSR);
objSR = null;
mobjResultsDataView = new DataView();
mobjResultsDataView = objDS.Tables[0].DefaultView;
}
//Finish up
objSearcher.Close();
bResult = true;
}
catch (Exception e)
{
mstrError = "Exception: " + e.Message;
}
finally
{
objSearcher = null;
objAnalyzer = null;
}
return bResult;
}
Above is the code i am using for search and the xml i am binding to the listview, now i need to tag the particular keywords found in the respective document and display it in the listview as recordsss,simlar to the below listview
No FileName KeyWord(s)Found
1 Test.Doc karthik
2 Test2.Doc steven
i hope u guys undesrtood the question,
This depends on how your documents were indexed. You'll need to extract the original content, pass it through the analyzer to get the indexed tokens, and check which matches the generated query.
Just go with the Highlighter.Net package, part of contrib, which does this and more.
I have form with dynamic file upload:
var ordinaryPropertyValue = new Catalog.Core.Entities.OrdinaryPropertyValue();
var fileFile = Request.Files["File" + prop.Id];
if (fileFile == null) continue;
string pathFile = Server.MapPath("~/temp");
string filenameFile = Path.GetFileName(fileFile.FileName);
if (!string.IsNullOrEmpty(filenameFile)) {
fileFile.SaveAs(Path.Combine(pathFile, filenameFile));
ordinaryPropertyValue.Value = Path.Combine(pathFile, filenameFile);
instance.SetPropertyValue(prop.Id, ordinaryPropertyValue);
}
How can I rename files which are submiited from users?
just set file name you want in this line
String filenameFile = "MyFile.ext";
String pathFile = Server.MapPath("~/temp/" + filenameFile);
fileFile.SaveAs(pathFile);
this will save your file in path ~/temp/MyFile.ext