0

Estou na luta aqui nesse projeto com asp.net, mais as classe estão certas como peguei em um tutorial aqui na net, elas não dão erro nenhum só quando executa o projeto ai mostra.

Erro CS0103 O nome "gvFiles" não existe no contexto atual

tenho a class CS.aspx.cs

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.Net;
using System.Data;

public partial class CS : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {
        //FTP Server URL.
        string ftp = "ftp://10.0.0.101:2323";

        //FTP Folder name. Leave blank if you want to list files from root folder.
        string ftpFolder = "Uploads/";

        try
        {
            //Create FTP Request.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder);
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            //Enter FTP Server credentials.
           // request.Credentials = new NetworkCredential("Username", "Password");
            request.UsePassive = true;
            request.UseBinary = true;
            request.EnableSsl = false;

            //Fetch the Response and read it using StreamReader.
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            List<string> entries = new List<string>();
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                //Read the Response as String and split using New Line character.
                entries = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }
            response.Close();

            //Create a DataTable.
            DataTable dtFiles = new DataTable();
            dtFiles.Columns.AddRange(new DataColumn[3] { new DataColumn("Name", typeof(string)),
                                                    new DataColumn("Size", typeof(decimal)),
                                                    new DataColumn("Date", typeof(string))});

            //Loop and add details of each File to the DataTable.
            foreach (string entry in entries)
            {
                string[] splits = entry.Split(new string[] { " ", }, StringSplitOptions.RemoveEmptyEntries);

                //Determine whether entry is for File or Directory.
                bool isFile = splits[0].Substring(0, 1) != "d";
                bool isDirectory = splits[0].Substring(0, 1) == "d";

                //If entry is for File, add details to DataTable.
                if (isFile)
                {
                    dtFiles.Rows.Add();
                    dtFiles.Rows[dtFiles.Rows.Count - 1]["Size"] = decimal.Parse(splits[4]) / 1024;
                    dtFiles.Rows[dtFiles.Rows.Count - 1]["Date"] = string.Join(" ", splits[5], splits[6], splits[7]);
                    string name = string.Empty;
                    for (int i = 8; i < splits.Length; i++)
                    {
                        name = string.Join(" ", name, splits[i]);
                    }
                    dtFiles.Rows[dtFiles.Rows.Count - 1]["Name"] = name.Trim();
                }
            }

            //Bind the GridView.
            gvFiles.DataSource = dtFiles;
            gvFiles.DataBind();
        }
        catch (WebException ex)
        {
            throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
        }
    }

    protected void DownloadFile(object sender, EventArgs e)
    {
        string fileName = (sender as LinkButton).CommandArgument;

        //FTP Server URL.
        string ftp = "ftp://10.0.0.101:2323";

        //FTP Folder name. Leave blank if you want to Download file from root folder.
        string ftpFolder = "Uploads/";

        try
        {
            //Create FTP Request.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            //Enter FTP Server credentials.
           // request.Credentials = new NetworkCredential("Username", "Password");
            request.UsePassive = true;
            request.UseBinary = true;
            request.EnableSsl = false;

            //Fetch the Response and read it into a MemoryStream object.
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            using (MemoryStream stream = new MemoryStream())
            {
                //Download the File.
                response.GetResponseStream().CopyTo(stream);
                Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(stream.ToArray());
                Response.End();
            }
        }
        catch (WebException ex)
        {
            throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
        }
    }
}

e tenho a outra classe chamada CS.aspx

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.Net;
using System.Data;

public partial class CS : System.Web.UI.Page
{


    protected void Page_Load(object sender, EventArgs e)
    {
        //FTP Server URL.
        string ftp = "ftp://10.0.0.101:2323";

        //FTP Folder name. Leave blank if you want to list files from root folder.
        string ftpFolder = "Uploads/";

        try
        {
            //Create FTP Request.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder);
            request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            //Enter FTP Server credentials.
           // request.Credentials = new NetworkCredential("Username", "Password");
            request.UsePassive = true;
            request.UseBinary = true;
            request.EnableSsl = false;

            //Fetch the Response and read it using StreamReader.
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            List<string> entries = new List<string>();
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                //Read the Response as String and split using New Line character.
                entries = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }
            response.Close();

            //Create a DataTable.
            DataTable dtFiles = new DataTable();
            dtFiles.Columns.AddRange(new DataColumn[3] { new DataColumn("Name", typeof(string)),
                                                    new DataColumn("Size", typeof(decimal)),
                                                    new DataColumn("Date", typeof(string))});

            //Loop and add details of each File to the DataTable.
            foreach (string entry in entries)
            {
                string[] splits = entry.Split(new string[] { " ", }, StringSplitOptions.RemoveEmptyEntries);

                //Determine whether entry is for File or Directory.
                bool isFile = splits[0].Substring(0, 1) != "d";
                bool isDirectory = splits[0].Substring(0, 1) == "d";

                //If entry is for File, add details to DataTable.
                if (isFile)
                {
                    dtFiles.Rows.Add();
                    dtFiles.Rows[dtFiles.Rows.Count - 1]["Size"] = decimal.Parse(splits[4]) / 1024;
                    dtFiles.Rows[dtFiles.Rows.Count - 1]["Date"] = string.Join(" ", splits[5], splits[6], splits[7]);
                    string name = string.Empty;
                    for (int i = 8; i < splits.Length; i++)
                    {
                        name = string.Join(" ", name, splits[i]);
                    }
                    dtFiles.Rows[dtFiles.Rows.Count - 1]["Name"] = name.Trim();
                }
            }

            //Bind the GridView.
            gvFiles.DataSource = dtFiles;
            gvFiles.DataBind();
        }
        catch (WebException ex)
        {
            throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
        }
    }

    protected void DownloadFile(object sender, EventArgs e)
    {
        string fileName = (sender as LinkButton).CommandArgument;

        //FTP Server URL.
        string ftp = "ftp://10.0.0.101:2323";

        //FTP Folder name. Leave blank if you want to Download file from root folder.
        string ftpFolder = "Uploads/";

        try
        {
            //Create FTP Request.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            //Enter FTP Server credentials.
           // request.Credentials = new NetworkCredential("Username", "Password");
            request.UsePassive = true;
            request.UseBinary = true;
            request.EnableSsl = false;

            //Fetch the Response and read it into a MemoryStream object.
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            using (MemoryStream stream = new MemoryStream())
            {
                //Download the File.
                response.GetResponseStream().CopyTo(stream);
                Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.BinaryWrite(stream.ToArray());
                Response.End();
            }
        }
        catch (WebException ex)
        {
            throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
        }
    }
}

em uma classe tenho o ID com o nome que esta dando o erro gvFiles, e a outra chama esse ID para montar o GridView.

alguma solução?

1
  • Bem vinda ao StackOverflow. No seu segundo código você colou errado. Era pra ser uma página aspx como você especificou e não o .cs que já colou anteriormente. Commented 10/01/2019 às 22:33

1 Resposta 1

1

Apesar de você não ter postado o seu aspx ainda seu erro está bem óbvio. Ele explicitamente informa que o gvFiles não existe no contexto atual.

Ao que tudo indica gvFiles é um Grid View, devido ao gv no inicio do nome e do DataSource que está sendo atribuído a ele.

Se você criou um Grid View no seu aspx ele está com o nome errado. Verifique se existe algo assim no seu aspx:

<asp:GridView ID="gvFiles" runat="server" Width="600px"></asp:GridView>

Note que se existir o atributo ID dele não está como gvFiles e por isso você recebe o erro:

Erro CS0103 O nome "gvFiles" não existe no contexto atual

1
  • entao eu conseguir resolver depois de horas analisando, era que a class nao estava enxergando a outra Commented 11/01/2019 às 1:20

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .