How search a file by its name and open it? [duplicate] - c#

This question already has an answer here:
How to open a pdf file in a WebForm application by search?
(1 answer)
Closed 7 years ago.
Currently i'm doing a web application project in ASP.net C#.
Here i have a problem to search a file by its name. Below code is shows were i did, but the problem is, it does not shows the file according to the search name, since it show all file name in directories.
Another problem is, i don't how to open the search files. Can any one help me?
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
string[] pdffiles = Directory.GetFiles(#
"\\192.168.5.10\\fbar\\REPORT\\CLOTHO\\H2\\REPORT\\", "*.pdf", SearchOption.AllDirectories);
string search = TextBox1.Text;
ListBox1.Items.Clear();
foreach(string file in pdffiles)
{
ListBox1.Items.Add(Path.GetFileName(file));
}
TextBox1.Focus();
} else
{
Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
}
}

First you have to use your search variable to filter out intended files
protected void Button1_Click(object sender, EventArgs e)
{
string search = TextBox1.Text;
if (TextBox1.Text != "")
{
string[] pdffiles = Directory.GetFiles(#"\\192.168.5.10\\fbar\\REPORT\\CLOTHO\\H2\\REPORT\\", string.Format("*{0}*.pdf",search), SearchOption.AllDirectories);
ListBox1.Items.Clear();
foreach (string file in pdffiles)
{
ListBox1.Items.Add(Path.GetFileName(file));
}
TextBox1.Focus();
}
else
{
Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
}
}
Now to open selected file.
protectecd void ListBox1_SelectedIndexChanged(object sender,EventArgs e)
{
string fileName= ListBox1.SelectedItem.ToString();
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition",string.Format("attachment; filename={0}",filename));
Response.TransmitFile(fileName);
Response.End();
}

you need to use your string search to check if file matches it
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
File[] pdffiles = Directory.GetFiles(#"\\192.168.5.10\fbar\REPORT\CLOTHO\H2\REPORT\", "*.pdf", SearchOption.AllDirectories);
string search = TextBox1.Text;
ListBox1.Items.Clear();
foreach (var file in pdffiles)
{
if(file.Name==search)
{
ListBox1.Items.Add(Path.GetFileName(file));
}
}
TextBox1.Focus();
}
else
{
Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
}
}
Also notice you have written the path in GetFiles function

I think the path should be #"\\192.168.5.10\fbar\REPORT\CLOTHO\H2\REPORT\". Also, Directory.EnumerateFiles might be more efficient.
Here's how I would search for any files that CONTAIN the searchName
using System.Linq;
string reportDirectoryName = "..."; // fill in with full path
string searchName = TextBox1.Text;
if (string.IsNullOrWhitespace(searchName))
return ...;
var files = Directory.EnumerateFiles(reportDirectoryName, "*.pdf", SearchOption.AllDirectories);
.Select(n => Path.GetFileName(n))
.Where(n => n.Contains(searchName);
ListBox1.Items.Clear();
ListBox1.Items.Add(files);

Related

Uploaded images are not found in folder asp.net

I have a upload function where it displays the uploaded image in a grdiview after the upload click.
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "~/Uploads/" + fileName));
}
GridView1.DataSource = files;
GridView1.DataBind();
}
}
protected void Upload(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Uploads/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}
This works fine. It uploads and shows in the gridview. The problem I have is that the pictures are not directed to the path. Its not in the uploads folder.
Any tricks on this?
UPDATE
Show all in solution explorer and i got this:
On possible solution could be, when saving/uploading files, use Path.Combine
FileUpload1.PostedFile.SaveAs( Path.Combine(Server.MapPath("~/Uploads/"),fileName))
and similarly for:
files.Add(new ListItem(fileName,Path.Combine(Server.MapPath("~/Uploads/"),fileName)));
Mostly i used following approach.
you can get help from following example code...
string fnam, newname,ext, serpath,dbpath="", fid;
ext = System.IO.Path.GetExtension(File_Upload.PostedFile.FileName);
fnam = File_Upload.PostedFile.FileName;
fid = Guid.NewGuid().ToString();
newname = fid + ext;
serpath = Path.Combine(Server.MapPath("uploads\\"), newname);
dbpath = "~\\uploads\\" + newname;
File_Upload.PostedFile.SaveAs(serpath);

How do I save some files under a directory in a new directory after making some changes

I opened a directory and I read some files in that directory amd made some changes, now I want to save the changes with the same file names at F:\BI\Out\ and keep the original files.
when I added these two lines
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
I was able to save the files under the new folder\Out,
but when I opened them I found that only one file is changed correctly and all the other files the old words are replace by blank space not by the new words.
Can anyone help me Thanks
string text = "";
string[] files;
private void Form1_Load(object sender, EventArgs e)
{
try
{
files = Directory.GetFiles(#"F:\BI\In\", "*.*", SearchOption.AllDirectories);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEtlPath.Text == "")
{
MessageBox.Show("Please Enter path");
txtEtlPath.Focus();
}
else
{
foreach (string file in files)
{
if (System.IO.File.Exists(file))
{
text = File.ReadAllText(file);
text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI");
text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW");
text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim());
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
}
Within your foreach () loop:
If you want the subfolder structure of the files found, do a replace on the filepath:
var outFilePath = file.Replace(#"F:\BI\In\", #"F:\BI\Out\");
You will need to create the subfolder before you can write the changed file:
new FileInfo(outFilePath)).Directory.Create();
If you don't want the subfolders, you can write directly into the top folder:
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
Writing is simple, just keep in mind there is an optional encoding parameter:
File.WriteAllText(outFilePath, text);

How to view selected item in listbox in image viewer asp.net

I have this code that populates my listbox that contains what I type in the textbox. My problem is how can I view the selected item in my listbox in a image viewer since all my files are images? Am I missing something?
Here's my code:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/images"), "*.*", SearchOption.AllDirectories);
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
ListBox1.Items.Add(fileName);
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DocumentImage.ImageUrl = Directory.GetDirectories("~/images") + ListBox1.SelectedItem.ToString();
}
This should work I think:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/images"), "*.*", SearchOption.AllDirectories);
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
string subPath = item.Substring(Server.MapPath("~/images").Length).Replace("\\","/");
ListBox1.Items.Add(new ListItem(fileName, subPath));
}
}
}
In this part, you need to not only have the file name, but also the path where the file was found. In my sample, the sub path where the file was found is first set into subPath and that is then stored as the value for the list item.
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DocumentImage.ImageUrl = "~/images" + ListBox1.SelectedItem.Value;
}
Here we use the sub path to set the correct url to the image.
Note that you need to have the AutoPostBack set to true on the DocumentImage in your asxp page in order for the image to change when you change the selection in the list box.

Loading large amount of text files from a share drive to search for a world. C#

Im trying to perform a search in a share drive that contains at least 90,000 files.
The code below is what I have:
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("No folder: Not listed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
List<string> allFiles = new List<string>();
AddFilesnames(sourceFolder, allFiles);
foreach (string fileName in allFiles)
{
string contents = File.ReadAllText(fileName);
if (contents.Contains(searchword))
{
listBox1.BeginUpdate();
listBox1.Items.Add(fileName);
listBox1.EndUpdate();
label4.Text = (Convert.ToInt32(label4.Text) + 1).ToString();
}
}
if (listBox1.Items.Count == 0)
{
MessageBox.Show("no files");
}
}
}
public void listboxtofile()
{
DialogResult resDialog = dlgSaveFile.ShowDialog();
if (resDialog.ToString() == "OK")
{
FileInfo fi = new FileInfo(dlgSaveFile.FileName);
StreamWriter sw = fi.CreateText();
foreach (string sItem in listBox1.Items)
{
sw.WriteLine(sItem);
}
sw.Close();
}
}
public void AddFilesnames(string sourceDir, List<string> allFiles)
{
string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
DateTime from1 = dateTimePicker1.Value.Date;
DateTime to1 = dateTimePicker2.Value.Date;
DateTime creationTime = File.GetCreationTime(fileName);
if (creationTime >= from1 && creationTime <= to1)
{
allFiles.Add(fileName);
}
}
//Recursion
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir);
foreach (string item in subdirectoryEntries)
{
// Avoid "reparse points"
if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
AddFileNamesToList(item, allFiles);
label4.Text = (Convert.ToInt32(label4.Text) + 1).ToString();
}
}
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
textBox1.Clear();
}
private void button5_Click(object sender, EventArgs e)
{
listboxtofile();
}
}
}
So far this is working with 3,000 files but I need to have access to a shared drive that contains 90,000 files and when I try to search in the share drive the windows form get frozen. I will really apreciate any help from you all.
My suggestion would be to do any file system work in a separate thread. If you do the file searching in the same thread as your form, Windows has no chance to update the form. You won't be able to update any of your form controls (like listBox1) directly from the new thread, but you can look into delegates and C# threading in general for ways to work around this.
Also, if you just need to search files for a specific word, have you looked into existing tools like grep?

Downloading csv files with zip?

I have this codes, the problem is, whenever I press the download button, it gives an error indicating Directory Not Found. I have already an upload function with the following fileUpload.PostedFile.SaveAs(Server.MapPath("~/Upload")); Below is my codes:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var files = Directory.GetFiles(#"~/Upload");
gvFiles.DataSource = from f in files
select new
{
FileName = Path.GetFileName(f)
};
gvFiles.DataBind();
}
}
protected void btnDownload_Click(object sender, EventArgs e)
{
string fileName = string.Empty;
string filepath = Request.MapPath("~/Upload");
string downloadFileName = "Attendance.zip";
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + downloadFileName);
using (ZipFile zip = new ZipFile())
{
foreach (GridView row in gvFiles.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSelect");
if (cb != null && cb.Checked)
{
fileName = (row.FindControl("lblFileName") as Label).Text;
zip.AddFile(Server.MapPath(Path.Combine(filepath, fileName)), "");
}
}
zip.Save(Response.OutputStream);
}
}
Can anyone help me with this please? When I use Directory.GetFiles(#"~/Upload"), I get the mentioned error
Directory.GetFiles expects an existing local path, die ~ Syntax is not possible here. Use MapPath before:
var files = Directory.GetFiles(Request.MapPath("~/Upload"));

Categories