程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> c#-讀取文件夾中的所有圖片文件

c#-讀取文件夾中的所有圖片文件

編輯:編程綜合問答
讀取文件夾中的所有圖片文件

我第一次讀取的時候沒有問題。在刪除圖片後再讀取圖片會讀取錯誤,以下是我的代碼各位幫忙看一下。

後台代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Data;

public partial class admin_netshopper_DHweihu_makepage_addhuandeng : System.Web.UI.UserControl
{
    public string SlideFolderPath = myConfig.webimgshijiurl + "/kuaigou/huandeng/";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!System.IO.Directory.Exists(SlideFolderPath))
            {
                System.IO.Directory.CreateDirectory(SlideFolderPath);
            }
            bind();
        }
    }
    public void bind()
    {
        string Images = "";
        string[] Dir = System.IO.Directory.GetFiles(SlideFolderPath);
        foreach (string file in Dir)
        {
            System.IO.FileInfo FI = new System.IO.FileInfo(file);
            if (FI.Extension == ".jpg")
            {
                string name = FI.Name.Substring(0, FI.Name.Length - 4);// 獲取文件名
                string URL = myConfig.webimgurl + "/kuaigou/huandeng/" + FI.Name;// 組裝圖片路徑
                Images += URL + "," + name + ",";
            }
        }
        DataTable table = new DataTable();// 創建一個表
        table.Columns.Add("URL");// 創建字段
        table.Columns.Add("id");
        string str = Images;
        if (str.Length > 0)
        {
            str = str.Substring(0, str.Length - 1);
        }
        string[] ss = str.Split(',');
        DataRow row = table.NewRow();
        for (int i = 0; i < ss.Length; i++)// 為表插入數據
        {
            if (i % 2 == 0) row = table.NewRow();
            row[i % 2] = ss[i];
            if ((i + 1) % 2 == 0) table.Rows.Add(row);
        }
        LblNumber.Text = table.Rows.Count.ToString();
        if (table.Rows.Count > 0)
        {
            GV.DataSource = table;
            GV.DataBind();
            divNumber.Style.Add("display", "block");
        }
        else
        {
            GV.DataSource = null;
            GV.DataBind();
            divNumber.Style.Add("display", "none");
        }
        if (GV.Rows.Count == 1)
        {
            Button BtnDelete = (Button)GV.Rows[0].Cells[1].FindControl("BtnDelete");
            BtnDelete.Enabled = false;
        }
    }
    protected void BtnDtal_Click(object sender, EventArgs e)
    {
        int Number = 0;
        string[] Dir = System.IO.Directory.GetFiles(SlideFolderPath);
        foreach (string file in Dir)
        {
            System.IO.FileInfo FI = new System.IO.FileInfo(file);
            if (FI.Extension == ".jpg")// 統計一共有多少個後綴為*.jpg的圖片文件
            {
                Number++;
            }
        }
        if (FUDtal.PostedFile.FileName == "")
        {
            Page.ClientScript.RegisterStartupScript(GetType(), "rsnn14", "<script>alert('請選擇圖片');</script>");
            return;
        }
        if (Number == 0)
        {
            Number = 1;
        }
        else if (Number > 0)
        {
            Number = Number + 1;
        }
        string name = FUDtal.PostedFile.FileName;//獲取文件名稱
        int index = name.LastIndexOf(".");
        string lastName = name.Substring(index, name.Length - index);//文件後綴
        string Newname = Number.ToString() + lastName;//文件名
        // || lastName == ".bmp" || lastName == ".gif" || lastName == ".png"
        if (lastName == ".jpg")
        {
            System.Drawing.Image image = System.Drawing.Image.FromStream(FUDtal.PostedFile.InputStream);
            int height = image.Height;
            int width = image.Width;

            if (height == 481 && width == 1920)
            {
                string path = SlideFolderPath + Newname;
                FUDtal.PostedFile.SaveAs(path);//保存到服務器上  
                Page.ClientScript.RegisterStartupScript(GetType(), "rsnn2", "<script>alert('圖片上傳成功');</script>");
                bind();
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "rsnn12", "<script>alert('圖片尺寸錯誤');</script>");
                return;
            }
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(GetType(), "rsnn17", "<script>alert('圖片後綴錯誤!');</script>");
            return;
        }
    }
    protected void BtnDelete_Click(object sender, EventArgs e)
    {
        int row = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
        HiddenField HFid = (HiddenField)GV.Rows[row].Cells[0].FindControl("HFid");
        string Route = SlideFolderPath + HFid.Value + ".jpg";
        FileInfo file = new FileInfo(Route);//指定文件路徑
        if (file.Exists)//判斷文件是否存在
        {
            file.Attributes = FileAttributes.Normal;//將文件屬性設置為普通,比方說只讀文件設置為普通
            file.Delete();//刪除文件
            if (file.Exists == false)
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "rsnn3", "<script>alert('圖片刪除成功');</script>");
                bindReset();
                bind();
            }
            else
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "rsnn16", "<script>alert('圖片刪除失敗');</script>");
                return;
            }
        }
    }
    public void bindReset()// 重新命名圖片
    {
        string Images = "";
        string[] Dir = System.IO.Directory.GetFiles(SlideFolderPath);
        foreach (string file in Dir)
        {
            System.IO.FileInfo FI = new System.IO.FileInfo(file);
            if (FI.Extension == ".jpg")
            {
                string name = FI.Name.Substring(0, FI.Name.Length - 4);// 獲取文件名
                Images += name + ",";
            }
        }
        DataTable table = new DataTable();// 創建一個表
        table.Columns.Add("id");// 創建字段
        string str = Images;
        if (str.Length > 0)
        {
            str = str.Substring(0, str.Length - 1);
        }
        string[] ss = str.Split(',');
        DataRow row = table.NewRow();
        for (int i = 0; i < ss.Length; i++)// 為表插入數據
        {
            if (i % 1 == 0) row = table.NewRow();
            row[i % 1] = ss[i];
            if ((i + 1) % 1 == 0) table.Rows.Add(row);
        }
        for (int i = 0; i < table.Rows.Count; i++)
        {
            string id = table.Rows[i]["id"].ToString();
            string srcFileName = SlideFolderPath + id + ".jpg";
            string destFileName = SlideFolderPath + (i + 1) + ".jpg";
            if (System.IO.File.Exists(srcFileName))
            {
                System.IO.File.Move(srcFileName, destFileName);// 重新命名圖片
            }
        }
    }
}

前台代碼

 <%@ Control Language="C#" AutoEventWireup="true" CodeFile="addhuandeng.ascx.cs" Inherits="admin_netshopper_DHweihu_makepage_addhuandeng" %>
<div style="width: 1024px; -moz-box-shadow: 0px 0px 10px #BFBFBF; -webkit-box-shadow: 0px 0px 10px #BFBFBF;
    box-shadow: 0px 0px 10px #BFBFBF; padding: 20px 5px; margin: 50px auto">
    <div style="width: 98%; margin-left: auto; margin-right: auto;">
        <asp:FileUpload ID="FUDtal" runat="server" />
        <asp:Button ID="BtnDtal" runat="server" Text="上傳" Height="30px" OnClick="BtnDtal_Click" />
        後綴: *.jpg(注:圖片格式為寬:1920px、高:481px)
    </div>
    <div style="width: 98%; margin: 20px auto 0px auto;">
        <div id="divNumber" runat="server" style="width: 100%; text-align: left; display: block;
            margin-bottom: 5px;">
            當前共有<asp:Label ID="LblNumber" runat="server"></asp:Label>張圖片
        </div>
        <asp:GridView ID="GV" runat="server" Width="100%" CellPadding="4" ForeColor="#333333"
            GridLines="None" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="圖片">
                    <ItemTemplate>
                        <asp:Image ID="Images" runat="server" Width="900px" ImageUrl='<%# Eval("URL") %>' />
                        <asp:HiddenField ID="HFid" runat="server" Value='<%# Eval("id") %>' />
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" />
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="操作">
                    <ItemTemplate>
                        <asp:Button ID="BtnDelete" runat="server" Text="刪除" Width="40px" Height="30px" OnClick="BtnDelete_Click" />
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" />
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
            </Columns>
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>
    </div>
</div>

最佳回答:


你在BtnDelete_Click事件中,刪除成功後調用了bindReset()後又調用bind(),這其中會不會有沖突?

etywu
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved