需要帮助以使用C#上传文件 [英] Need help to upload file using C#

查看:117
本文介绍了需要帮助以使用C#上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我试图通过在C#控制台中编写程序在php服务器上上传文件
它每5分钟读取一次文件,然后将文件上传到服务器上
但是我的代码给我错误无法连接到服务器"

请帮助我为本地文件和在线服务器设置正确的路径.





Hi
i am trying to upload file on my php server by writing program in C# console
it read the file for every 5 minutes and upload the file on the server
but my code is giving me error "unable to connect to server"

please help me to set the paths right for local file and online server .





static void Main(string[] args)
        {
            StreamReader streamReader = new StreamReader("C:\\wamp\\www\\FTCPC\\logfile.txt");
            ArrayList lines = new ArrayList();

            string line;

            while ((line = streamReader.ReadLine()) != null)
            {
                lines.Add(line);
            }
            streamReader.Close();

            if (lines.Count > 0)
            {
                Console.Write(lines[lines.Count - 1].ToString());
               
            }

            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential("username", "password", "server info ");

            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader("C:\\wamp\\www\\FTCPC\\logfile.txt");
            byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            sourceStream.Close();
            request.ContentLength = fileContents.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

            response.Close();



            Console.WriteLine("\\n");
            Console.ReadLine();

        }

推荐答案

request.Credentials = new NetworkCredential("username", "password", "server info ");



我认为您已更改此设置,因此我们看不到您的用户名和密码?如果是这样,那么最好确保您可以连接到该计算机上的FTP站点,检查防火墙是否允许您的程序通过,等等,从而最好地调试"代码无法连接的错误.



I assume you changed this so we could not see your username and password ? If so, then an error that your code cannot connect is best ''debugged'' by making sure you can connect to your FTP site in general on that machine, checking your firewall is letting your program through, etc.


这篇关于需要帮助以使用C#上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆