I have uploaded files to the server using AsyncFileUpload. How can I display the existing files from the folder using asp.net web forms.? I would like to provide a link to the word document to open the file or save it. I couldn't find any example online. Please let me know. Thanks.
Sample code:
Markup:
<asp:gridView runat="server" id="grid" >
<columns>
<asp:HyperLinkColumn DataTextField="Name" DataNavigateUrlField='<%#Eval(Server.MapPath("FullName")) %>' Target="_blank" />
</columns>
</asp:GridView>
Code behind:
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("YourDirectory"));
FileInfo [] files = dirInfo.GetFiles();
grid.DataSource=files;
grid.DataBind();
You would need to simply get the list of files in that directory using Directory.GetFiles (http://msdn.microsoft.com/en-us/library/07wt70x2.aspx) and then display a suitable list using a gridview or repeater etc.
Related
I am using this code on button click from which I can download a file with a specific name.
But I want, when the user has uploaded a file, in his details like any Id proof details file.
Now to verify the user admin want to see the his Id proof details.
So he will download the file which user had uploaded and that is saved in database.
So the file can be in any type or extension.
private void Button1_click(object sender, System.EventArgs e)
{
string filename="C:\myuploads\invoice.pdf";
Response.ContentType = "Application/pdf";
Response.AppendHeader("Content-Disposition", "attachment;" + filename +);
Response.TransmitFile(Server.MapPath(filename));
Response.End();
}
I think this is what you're after.
private void DownloadFile(string file)
{
var fi = new FileInfo(file);
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename="+ fi.Name);
Response.WriteFile(file);
Response.End();
}
So you just call it like this:
string myfile = #"c:\path\To\Files\myFile.pdf"; //this wouldn't be a static string in your code
DownloadFile(myfile);
Thanks for answering my questions. My LinkButton to downloading the file from database on particular user Id worked Successfully.
Actually My Download Link was in update panel so It needs the "Trigger" for this.. And My Link was in GridView So I had Passed the Link Button Id in Trigger.
Whenever we use GridView in Update Panel and There is a LinkButton to Download the File from database on particular user Id. We Should Pass **GridView Id not the LinkButton Id in Template Field.**
<asp:UpdatePanel ID="upd" runat="server">
<ContentTemplate>
<asp:GridView ID="grd_UserList" runat="server" CssClass="table"
DataKeyNames="Uid" AutoGenerateColumns="false" AllowPaging="false">
<asp:TemplateField HeaderText="Task Name">
<ItemTemplate>
<asp:LinkButton Id="LinkDownload" runat="Server" CommandArgument='<%# Eval("Attachment") %>' >
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="grd_UserList" />
</Triggers>
</asp:UpdatePanel>
When the user uploads the file, you should be able to use the ContentType property of the posted file. This is assuming you used a file upload control like:
<asp:FileUpload ID="uploadFile" runat="server" />
When the file is uploaded, get the content type using
string fileType = uploadFile.PostedFile.ContentType
Save that value in your DB, and use it as the value of Reponse.ContentType in your existing code, when you download it later.
I have made an application that successfully display the files in folder in a asp:GridView and allows the user to download.
Here is my code behind:
string[] filePaths = Directory.GetFiles(Server.MapPath(strDirectory));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
files.Add(new ListItem(Path.GetFileName(filePath), filePath));
}
GridView1.DataSource = files;
GridView1.DataBind();
Here is my GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
EmptyDataText = "No files uploaded" CssClass="mGrid" PageSize="20"
AllowPaging="True" AlternatingRowStyle-CssClass="alt"
OnPageIndexChanging="GridView1_PageIndexChanging" PagerStyle-CssClass="pgr">
<Columns>
<asp:BoundField DataField="Text" HeaderText="File Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text = "Download"
CommandArgument = '<%# Eval("Value") %>' runat="server"
OnClick = "DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
What I want to do now is add the date modified in a gridview column so that my users will have an easier time finding the correct documents customers call about. How do I go about this?
You'll want to have more detail than the file name in the GridView as the Directory.GetFiles() method only returns paths. In your code, try using something like this instead of Directory.GetFiles():
DirectoryInfo di = new DirectoryInfo(Server.MapPath(strDirectory));
List<FileInfo> files = di.GetFiles().ToList();
GridView1.DataSource = files;
GridView1.DataBind();
The DirectoryInfo class provides much more detailed information about file system objects and gives you much more data (you can also filter based on file extension). By using this, you won't have to do any extra work to get details about the file and in your GridView, you'll have access to many properties of each file (including the modified date, name, and many others) by using the GetFiles() method of the DirectoryInfo class.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
EmptyDataText = "No files uploaded" CssClass="mGrid" PageSize="20"
AllowPaging="True" AlternatingRowStyle-CssClass="alt"
OnPageIndexChanging="GridView1_PageIndexChanging" PagerStyle-CssClass="pgr">
<Columns>
<asp:BoundField DataField="Name" HeaderText="File Name" />
<asp:BoundField DataField="LastWriteTime" HeaderText="Last Modified" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" Text = "Download"
CommandArgument = '<%# Eval("Name") %>' runat="server"
OnClick = "DownloadFile"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Directory Info Documentation: http://msdn.microsoft.com/en-us/library/ms143327(v=vs.110).aspx
File Info Documentation: http://msdn.microsoft.com/en-us/library/system.io.fileinfo(v=vs.110).aspx
Try this
File.GetLastWriteTime(path);
Here is complete detail
http://msdn.microsoft.com/en-us/library/system.io.file.getlastwritetime(v=vs.110).aspx
You need to use the FileInfo Class after getting the FilePaths. And this fileinfo has the properties like LastWriteTime,CreationTime , using these attributes you can sort and show. Like inside loop you need to use like this in code behind
FileInfo fi1 = new FileInfo(filePath );
and Use
fi1.LastWriteTime
Try:
DateTime date = directory.GetLastWriteTime;
for the file you can use
File.GetLastWriteTime
MSDN
I tried to get image Path from database with using eval but in cs part I get different path name.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" Value='<%#Eval("Path")%>' runat="server" />
<img alt="image" style="text-align: center" src="<%#Eval("Path")%>" /></a><asp:CheckBox
ID="CheckBox1" runat="server" />
<br></br>
</ItemTemplate>
</asp:Repeater>
and in .cs part I tied to get this path value but it brings me very different datapath
foreach (RepeaterItem item in Repeater1.Items)
{
CheckBox ch = (CheckBox)item.FindControl("CheckBox1");
HiddenField hf = (HiddenField)item.FindControl("HiddenField1");
if (ch.Checked)
{
Image_BLLcs ibll = new Image_BLLcs();
File.Delete(hf.Value);
ibll.Delete(hf.Value);
}
how can I solve these problem, can you help me?
for example
in my database path is equal image/images (3).jpg
but when I execute this code it shows this C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\image\images (3).jpg as a path.
I have used Server.MapPath and it solved my problem
File.Delete(Server.MapPath(hf.Value));
ibll.Delete(Server.MapPath(hf.Value));
What I'm trying to do here is have a datagrid show a list of files on the server which the user can click on to download, or open. The list populates with the files just fine, I get a whole list of all the pdf files in the folder. When I go to click on them in the datagrid, the link is directed to the application root directory and not to the proper folders. How do I tell a datagrid hyperlink column where to go?
C# code behind:
DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~") + "/Assets/reports/");
gridList.DataSource = dir.GetFiles("*.pdf");
gridList.DataBind();
asp
<asp:DataGrid runat="server" id="gridList" Font-Name="Verdana"
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name"
HeaderText="File Name"/>
</Columns>
</asp:DataGrid>
I tried placing this in:
NavigateUrl = '<%# "~/Assets/reports/" + Eval("Name") %>'>
but I get a "databinding expressions are only supported on objects that have a databinding event." error
Here you go.
<asp:HyperLinkColumn DataNavigateUrlField="Name"
DataTextField="Name"
HeaderText="File Name"
DataNavigateUrlFormatString="~\examfilemanager\{0}" />
Found it here.
asp.net DataGrid file structure and linking back to it
I'm trying to delete a record from Gridview1 at the same time delete the corresponding image file off the server in a single click. (Each row in Gridview1 has an associated image file on the server.)
To delete the record, I'm using asp:CommandField showDeleteButton="true" along with a sqlDataSource's DELETE statement.
During that process, I'm also using GridView1's "onRowDeleting" event to delete the corresponding image file off the server.
Here's what it does, with the code I have below:
The record indeed gets deleted,
The file on the server does not,
There are NO errors thrown (since I guess that it's not finding the file, and this is the expected behavior).
Also consider:
I've already set up and tested a much simpler "see if files can actually be deleted off the
server" test before I started development on the Gridview. Since our files are on a hosting
company server, I wanted to test for any permissions issues.
Whereby:
Enter the fileName and extension into a text box ("myImage.jpg")
Click the button that uses the File.Delete method
WhaaLa - the file is gone from the server.
However, I can't get the file to go away with my new setup.
Here's the code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="libraryID"
DataSourceID="SqlDataSource1" Width="800px" onrowdeleting="deleteImageFromServer" CssClass="gridViewSmallText"
OnDataBound="rowCount">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<%--A link that goes to the uploadPage to upload a new version of the image--%>
<asp:HyperLinkField runat="server" HeaderText="SKU (Click to Update)" DataTextField="sku" DataNavigateUrlFields="sku" SortExpression="sku" DataNavigateUrlFormatString="graphicUpload.aspx?sku={0}" >
</asp:HyperLinkField>
<asp:TemplateField HeaderText="Image" SortExpression="imagePath">
<ItemTemplate>
<%--Pull the imagePath column from the database here-it also includes the image file --%>
<asp:Image ID="merchImage" runat="server" Height="100px" ImageUrl='<%# "http://www.ourcompanysite.net/" + DataBinder.Eval(Container.DataItem, "imagePath") %>' /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="View Full Size">
<ItemTemplate>
<%--A link to view the image in it's full size in a new browser window--%>
<asp:HyperLink ID="fullSizeHyperlink" runat="server" NavigateUrl='<%# "http://www.leadingjewelersguild.net/" + DataBinder.Eval(Container.DataItem, "imagePath") %>' Text="View" Target="_blank" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateUpdated" </asp:BoundField>
<%---some date stuff here--%>
<asp:BoundField DataField="DateCreated" HeaderText="First Uploaded" SortExpression="DateCreated" >
</asp:BoundField>
</Columns>
</asp:GridView>
Code behind:
protected void deleteImageFromServer(object sender, GridViewDeleteEventArgs e)
{
// I read from GridViewGuy.com that you're supposed to reference the row item via e.Values
string imageToDelete = e.Values["sku"] + ".jpg";
//I pulled the value of "imageToDelete" into a lable just to see what I was getting
//during the "onRowDeleting" and it reported back .jpg instead of the full file name
//myImage.jpg, so I guess this is the crux of my problem.
string image = Server.MapPath("/images/graphicsLib/" + imageToDelete);
string image = Server.MapPath("e:\\sites\\oursite\\files\\images\\graphicsLib\\" + imageToDelete);
if (File.Exists(image))
{
File.Delete(image);
}
//at this point the record from GridView1 is gone, but the file on server remains.
}
I think part of your problem may be that in order for e.Values["sku"] to contain a value, it has to be bound first. I don't think HyperlinkField binds its data (I could be wrong on that though so don't quote me)
First try adding a <asp:BoundField DataField="sku" Visible="false" /> in your column list. or change the HyperLinkField to TemplateField and explicitly bind the sku '<%#Bind("sku")%>'
If that doesn't work you can try changing DataKeyNames="libraryID" to DataKeyNames="libraryID,sku". You should be able to get the value out of e.Keys["sku"], or e.Values["sku"].
After you started development using the GridView control, have you verified that the deleteImageFromServer method is being called by setting a breakpoint in there?
And that imageToDelete is being set correctly?
After breaking into it, look at the 'watch' values for 'sender' and 'e'. Drill down into those to see what kind of objects they are and what values they hold.
Sometimes you have to traverse the object hierarchy in the GridVied control to get to the right object.