读取文件夹中的所有图片文件

我第一次读取的时候没有问题。在删除图片后再读取图片会读取错误,以下是我的代码各位帮忙看一下。

后台代码

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>

2个回答

你在BtnDelete_Click事件中,删除成功后调用了bindReset()后又调用bind(),这其中会不会有冲突?

save4me
save4me 假设文件夹里面的图片是1.jpg,2.jpg,3.jpg...(按照你的代码,就算最初不是这个名字,在点击删除按钮后也会被命名成这样),那么再点击删除的时候,它们会被命名成1.jpg, 2.jpg,3.jpg...,可以发现新文件名会是1.jpg之类的,与文件夹现有的1.jpg重名,此时调用File.Move会抛出IOException
4 年多之前 回复
etywu
光明天使米迦勒 不会。
4 年多之前 回复

//    //读取assets文件夹的图片
    private Bitmap getBit(String filename){
        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inSampleSize = 2;//图片宽高都为原来的二分之一,即图片为原来的四分之......
答案就在这里:读取assets文件夹中的图片
----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐