How To Check If a File Exists In FTP Server in C#

Friends,

In my last post, we saw how can we delete a file from FTP server. However, there might be a situation when you try to delete a file and the file does not exist on the server. In this case, code will throw an error saying “550, File Unavailable“. To solve this, we must know whether a file exists on server before accessing the file. In this post, we will see how can we do the same.

Here’s the code –

        private bool CheckIfFileExistsOnServer(string fileName)
        {
            var request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);
            request.Credentials = new NetworkCredential("username", "password");
            request.Method = WebRequestMethods.Ftp.GetFileSize;

            try
            {
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                return true;
            }
            catch (WebException ex)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                    return false;
            }
            return false;
        }

As you see, we create an object of FtpWebRequest class and try to get the FileSize of the requested file. If the file exists, server will return the file size else it will throw an exception saying “File unavailable”. In the catch block, we are catching the exception and checking for the ResponseCode from the response. If the ResponseCode is “ActionNotTakenFileUnavailable“, this means the file is unavailable and we return to the calling method.

Hope you like this post. Keep learning & sharing! Cheers!

How To Delete a File From FTP Server in C#

Friends,

In my last post, we saw how can we retrieve the list of all files & folders from a FTP server using C#. In this post, we will see how can we delete a file from FTP server using C# from within your Console or Windows Forms Application.

Here’s the code –

     private string DeleteFile(string fileName)
     {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);
        request.Method = WebRequestMethods.Ftp.DeleteFile;
        request.Credentials = new NetworkCredential("username", "password");

        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        {
           return response.StatusDescription;    
        }
     }

The above code deletes a file named “test.zip” from the root location of the server “www.server.com”. If you see the code,we created an object of FtpWebRequest class and this time, we passed the RequestMethod as DeleteFile. This command tells the CLR to delete the mentioned file from the server. If the file is deleted, it sends a response in ResponseDescription as “250 File deleted successfully.

Hope you like this post! Keep learning and sharing! Cheers!

How To List All Files & Directories From a FTP Server in C#

Friends,

In this post, we will see how we can retrieve the list of files and directories from a FTP server in C#. We will make use of FtpWebRequest class to perform this action. FtpWebRequest class is defined in System.Net namespace. This means you need to use this namespace at the top of your program to use the FtpWebRequest class.

Let’s see a code sample to retrieve the list of files and directories from the root folder of server “www.server.com” –

 private List ListFiles()
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/");
                request.Method = WebRequestMethods.Ftp.ListDirectory;

                request.Credentials = new NetworkCredential("username", "password");
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);
                string names = reader.ReadToEnd();

                reader.Close();
                response.Close();

                return names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }
            catch (Exception)
            {
                throw;
            }
        }

In the above code, we create a request to ftp server using FtpWebRequest class and set the RequestMethod of the request to WebRequestMethods.Ftp.ListDirectory. In the next line, we define the credentials to be used on the server. Then we fire the request and get the response in FtpWebResponse object. The “ListDirectory” RequestMethod returns all data from server in  string format. Finally, we parse the response stream and split the returned data to get a list of all files & folders present on the server’s location.

Hope you like this post! Keep learning & sharing! Cheers!

How To Add a Sub-Domain to Your Website Using Control Panel in Arvixe

Friends,

This blog post will explain you the steps required to create a new sub-domain in your top-level domain from Control Panel of your Arvixe hosting. To start with, log into your Control Panel of Arvixe hosting and follow the below steps –

  • Click Domainssub-domain-arvixe-1
  • Click Add Domainsub-domain-arvixe-2
  • Click Sub-domainsub-domain-arvixe-3
  • Perform the following steps on this screen
    • Enter the name of your sub-domain
    • If you want to create a new website on your sub-domain, click “Create Web site”
    • Check “Enable DNS” & “Create Instant Alias” & click “Add”sub-domain-arvixe-4
  • You’re done. Your sub domain should be visible & accessible within minutes.

Hope you like this. Keep learning and sharing. Cheers.

Display Live Preview of your Webcam Stream in Windows Store App

Friends,

In this post, we will see how simple it is to stream a live preview from your webcam on a small screen in your Windows store App. You can use it to display user’s picture in the side of a screen or also can show what the camera is focusing on at a given instance. To do this, we will make use of 2 classes. One is CaptureElement control present in Windows.UI.Xaml.Controls and other is MediaCapture class present in Windows.Media.Capture namespace. This post will show how to instantiate the camera and display camera’s stream on the app as soon as the app loads. So, let’s get started –

  • Make sure you have added App capabilities to use Webcam + Microphone in App manifest file.
    <captureelement Name="capturePreview" Height="400" Width="400" HorizontalAlignment="Right" Margin="15"></captureelement>
    
  • On XAML page, we declare a CaptureElement control as below.
    protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
          MediaCapture captureMgr = new MediaCapture();
          await captureMgr.InitializeAsync();
          
          capturePreview.Source = captureMgr;
          await captureMgr.StartPreviewAsync();
    }
    
  • Inside the OnNavigatedTo() event hander, we will write the below code.
  • You’re done.

If you see the 2nd step above, we are 1st declaring an object of MediaCapture class and then we are calling the asynchronous InitializeAsync() to initialize the webcam. ON this line, you can also specify the webcam you want to use for the app. You can choose a webcam as discussed in this link. In the next line, we set the Source of the CaptureElement declared in Step 1 to the initialized webcam. In the final line, we call StartPreviewAsync() function of MediaCapture class to start displaying the webcam’s stream to the app.

Hope you liked reading this article. Keep learning & sharing. Cheers!

How To Get Access to Front & Back Camera in Windows 8.1 Store App

Friends,

In this post, we will see how can we get access specifically to Front camera/Back camera in our Windows 8/8.1 Store App. To get the access, we will use DeviceInformation class defined in Windows.Devices.Enumeration namespace. Below is the code snippet for the same –

DeviceInformationCollection webcamList = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);

DeviceInformation frontWebcam = (from webcam in webcamList
                                            where webcam.EnclosureLocation != null
                                            && webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front
                                            select webcam).FirstOrDefault();

DeviceInformation backWebcam = (from webcam in webcamList
                                            where webcam.EnclosureLocation != null
                                            && webcam.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
                                            select webcam).FirstOrDefault();

Hope you like this. Keep learning and sharing! Cheers!

How To Implement Select All/Unselect All CheckBoxes in GridView Rows

Friends,

In my last posts, I explained How To Add CheckBox to GridView and How To Get Selected Multiple Rows From GridView. In this post, I will explain how can  you select/unselect all rows of a GridView by selecting a CheckBox in client side.

We will start with using the same GridView, we are using in our previous examples. The only difference I will make here is add a CheckBox in the header of the Checkbox column using the HeaderTemplate clicking on which will toggle the state of checkboxes in each row of the GridView. To toggle the state of check boxes, we will use a little bit of jQuery. Below is the code for the same.

Code for ASPX Page:

<asp:gridview ID="grdData" runat="server" AutoGenerateColumns="False" CellPadding="4" CssClass="grdData"
            ForeColor="#333333" GridLines="None" Width="200">
            <alternatingrowstyle BackColor="White" ForeColor="#284775"></alternatingrowstyle>
            <columns>
                <asp:templatefield HeaderText="Select">
                    <headertemplate>
                        <input type="checkbox" id="chkAll" onclick="javascript: toggleCheckboxes()" />
                    </headertemplate>
                    <itemtemplate>
                        <asp:checkbox ID="cbSelect" CssClass="gridCB" runat="server"></asp:checkbox>
                    </itemtemplate>
                </asp:templatefield>
                <asp:boundfield DataField="ID" HeaderText="ID"></asp:boundfield>
                <asp:boundfield DataField="Name" HeaderText="Name"></asp:boundfield>
            </columns>
            <editrowstyle BackColor="#999999"></editrowstyle>
            <footerstyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></footerstyle>
            <headerstyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></headerstyle>
            <pagerstyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"></pagerstyle>
            <rowstyle BackColor="#F7F6F3" ForeColor="#333333"></rowstyle>
            <selectedrowstyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></selectedrowstyle>
            <sortedascendingcellstyle BackColor="#E9E7E2"></sortedascendingcellstyle>
            <sortedascendingheaderstyle BackColor="#506C8C"></sortedascendingheaderstyle>
            <sorteddescendingcellstyle BackColor="#FFFDF8"></sorteddescendingcellstyle>
            <sorteddescendingheaderstyle BackColor="#6F8DAE"></sorteddescendingheaderstyle>
        </asp:gridview>

Javascript/jQuery Code: To be used in header/footer of the page where the grid is loaded.

    <script type="text/javascript">
        function toggleCheckboxes() {
            if ($("#chkAll").prop('checked'))
                $(".gridCB input[type='checkbox']").prop('checked', true);
            else
                $(".gridCB input[type='checkbox']").prop('checked', false);
        }
    </script>

You’re done.

Hope you like this! Keep learning and sharing! Cheers!