18

これは、gridview1 と呼ばれる datagridviewer と fileupload1 を取得した取引です。ファイルをアップロードすると、gridview1 とデータベース内のテーブルがファイル名とパスで更新され、そのファイルがフォルダー "Mag" に保存されます...やりたいことは逆ですが、グリッドビューを使用してテーブルエントリを削除する方法を知りましたが、フォルダー「Mag」からファイルを削除しても機能しません C#またはコードビハインドで次のコードを使用しました

protected void GridView1_Del(object sender, EventArgs e)  
{
    string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
    string[] Files = Directory.GetFiles(@"i:/Website/WebSite3/Mag/");

    foreach (string file in Files)
    {
        if (file.ToUpper().Contains(DeleteThis.ToUpper()))
        {
            File.Delete(file);
        }
    }
}

それは私にエラーを与える

"オブジェクト参照がオブジェクト インスタンスに設定されていません。"

plsは私が何を間違っているのか教えてください。プラットフォームを深く理解する必要はありません。事前にマークに感謝します。

ここに私が見つけた答えがあります すべての答えについてタミーと他のみんなに感謝します

ここで、取引対象関数は、グリッドビューとデータベーステーブルからファイルの詳細を削除し、ファイルが保存されているプロジェクトフォルダーからファイルを削除します

含めたいグリッドビューのスクリプトセクションに

OnRowDeleting="FuntionName"

いいえ

OnSelectedIndexChanged = "FuntionName"

また

OnRowDeleted="FuntionName"

次にC#コード(コードビハインド)で

protected void FuntionName(object sender, GridViewDeleteEventArgs e)
    {
// storing value from cell
        TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];

// full path required
        string fileName = ("i:/Website/WebSite3/Mag/" + cell.Text); 

    if(fileName != null || fileName != string.Empty)
    {
       if((System.IO.File.Exists(fileName))) 
       {
           System.IO.File.Delete(fileName);
       }

     }
  }

そして、学びたい人のための追加の参考資料として

OnRowDeleting="FuntionName" は、行を削除する直前に、削除をキャンセルしたり、データに対して関数を実行したりできるようにするためのものです。

OnRowDeleted="FuntionName" 直接削除

4

5 に答える 5

51

これは私がファイルを削除する方法です

if ((System.IO.File.Exists(fileName)))
                {
                    System.IO.File.Delete(fileName);
}

また、削除で渡すファイル名が正確なパスであることを確認してください

編集

代わりに次のイベントを使用することも、このスニペットのコードを使用してメソッドで使用することもできます

void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
  {

    // Get the currently selected row using the SelectedRow property.
    GridViewRow row = CustomersGridView.SelectedRow;

    //Debug this line and see what value is returned if it contains the full path.
    //If it does not contain the full path then add the path to the string.
    string fileName = row.Cells[0].Text 

    if(fileName != null || fileName != string.empty)
    {
       if((System.IO.File.Exists(fileName))
           System.IO.File.Delete(fileName);

     }
  }
于 2013-01-10T05:37:57.340 に答える
1

私のプロジェクトでは ajax を使用しており、このようなコード ビハインドで Web メソッドを作成します

前に

 $("#attachedfiles a").live("click", function () {
            var row = $(this).closest("tr");
            var fileName = $("td", row).eq(0).html();
            $.ajax({
                type: "POST",
                url: "SendEmail.aspx/RemoveFile",
                data: '{fileName: "' + fileName + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () { },
                failure: function (response) {
                    alert(response.d);
                }
            });
            row.remove();
        });  

コードビハインドで

        [WebMethod]
        public static void RemoveFile(string fileName)
        {
            List<HttpPostedFile> files = (List<HttpPostedFile>)HttpContext.Current.Session["Files"];
            files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));

            if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName)))
            {
                System.IO.File.Delete(HttpContext.Current.Server.MapPath("~/Employee/uploads/" + fileName));
            }
        }

これが役立つと思います。

于 2013-01-10T07:05:10.500 に答える
1

GridView1.SelectedRow が null でないことを確認します。

if (GridView1.SelectedRow == null) return;
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;
于 2013-01-10T05:34:16.937 に答える
0
string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files. 
    foreach (string f in picList)
    {
        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path. 
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files. 
    foreach (string f in txtList)
    {

        // Remove path from the file name. 
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied. 
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied. 
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}
于 2015-06-01T11:59:28.833 に答える