Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17







C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

I have C# code that FTP files. This has worked without issue since the code was written.

Recently, I was given a new server location to drop these files. The only code changes I made were the FTP location and the credentials. No other code changes were made.

Anyway, when I run the code, it executes with no errors. Everything appears to have worked. But when I use an FTP client to make sure the files made it on to the FTP server, there's nothing there.

I reached out to the FTP site owner to ask him to check his FTP's log files. He said he sees me connecting and doing a transfer, but there's no files in the transfer.

FWIW, when I try to FTP files via the client, there are no issues.

I'm at a loss considering this worked with the old FTP site, and that I've changed no code other than the credentials.

Any ideas?

Thanks in advance for your help.
How to Use the Help Bell
LVL 10
How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

CheckBox[] boxes = new CheckBox[6];
            boxes[0] = checkBox1;
            boxes[1] = checkBox2;
            boxes[2] = checkBox3;
            boxes[3] = checkBox4;
            boxes[4] = checkBox5;
            boxes[5] = checkBox6;
            // C#
            // Set to details view.
            listView1.View = View.Details;
            // Add a column with width 20 and left alignment.
            listView1.Columns.Add("Instrument", 65, HorizontalAlignment.Left);
            listView1.Columns.Add("Bid", 65, HorizontalAlignment.Left);
            listView1.Columns.Add("Ask", 65, HorizontalAlignment.Left);
            listView1.Columns.Add("Last Price", 65, HorizontalAlignment.Left);

            string bal = RetrieveAccountBalance();

            var y = JsonConvert.DeserializeObject<List<AccountDetail>>(bal);

            for (var i = 0;i <= 6; i++)

                 if (boxes[i].Checked)
                    var s = boxes[i].Tag;

                    string x = "/market/" + s +"/AUD/tick";
                    string o = GetMarketTick(x); //{"bestBid":354.0,"bestAsk":356.89,"lastPrice":356.99,"currency":"AUD","instrument":"ETH","timestamp":1506254860,"volume24h":1183.241}

                    var h = JsonConvert.DeserializeObject<List<TickDetail>>(o);
                    for (var z = 0; z < h.Count; z++)
                        string[] row = { h[z].instrument, h[z].bestBid, h[z].bestAsk, h[z].lastPrice };

Open in new window

class Program
        public static void CalculateAge(int y, int m, int d)
                DateTime date = Convert.ToDateTime(y + "-" + m + "-" + d);
                var bday = float.Parse(date.ToString("yyyy.MMdd"));
                var now = float.Parse(DateTime.Now.ToString("yyyy.MMdd"));
                float age = (now - bday);
                if (now <= bday || age >= 135)
                    Console.WriteLine("Sorry, this is an Invalid Input of date.");

                    Console.WriteLine("Your Age is " + (age.ToString().Substring(0, age.ToString().LastIndexOf('.'))));

            catch (Exception ex)

        static void Main(string[] args)
            var day = "";
            var month = "";
            var year = "";
            int iDay, iMonth, iYear;
            Console.WriteLine("Hello, Welcome to Birthday Calculator!");
            Console.WriteLine("Please Enter your Birth Day: ");
            day = Console.ReadLine();
            while (!int.TryParse(day, out iDay))
                Console.WriteLine("Enter valid numeric day.");
                day = 

Open in new window

I used this below in VB flavor and it worked perfectly.

                SqlCommand cmd = new SqlCommand();
                int taxPayerID = 0;
                cmd.CommandText = "usp_TaxPayer";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@taxPayerFullName", txtfname.Text);
                cmd.Parameters.AddWithValue("@address", txtfaddress.Text);
                cmd.Parameters.AddWithValue("@city", txtcity.Text);
                cmd.Parameters.AddWithValue("@state", ddlstates.SelectedValue);
                cmd.Parameters.AddWithValue("@zip", txtfzip.Text);
                cmd.Parameters.AddWithValue("@pid", accountnumber.Text);
                cmd.Parameters.AddWithValue("@phone", txtOwnerPhone.Text);
                cmd.Connection = conn;

                SqlParameter tID = cmd.Parameters.Add("@taxPayerID", SqlDbType.Int);
                tID.Direction = ParameterDirection.Output;

                taxPayerID += Convert.ToInt32(tID.Value);

Open in new window

I converted to C# and now, I am getting an error that this:
taxPayerID += Convert.ToInt32(tID.Value);

Open in new window

Object cannot be cast from DBNULL to other types

Any ideas how to resolve?

Basically, I have one stored procedure that inserts records into the database and grabs the last inserted ID:

Open in new window

Then I am using that in another stored procedure:
ALTER PROCEDURE [dbo].[sp_saveMarineInfo] 
 @pid       int,
 @eID       int,
 @txYr        smallint,
 @marineRegno       varchar(50),
 @vesselRegno       varchar(50),
 @txretval          Money,
 @vtxretval         Money,
 @tID               int
  begin tran
  if exists (select * from MarineInfo where pid = @pid)
    UPDATE MarineInfo SET TaxYear = @txYr
      ,marineRegNo = @marineRegno
	  ,vesselRegNo = @vesselRegno
      ,TaxPyrRetdVal = @txretval
	  ,VesselTaxPyrRetdVal =@vtxretval
       where pid = @pid
    INSERT INTO [dbo].MarineInfo

Open in new window

With a parameter of tID and I am trying to assign a value from that parameter to tID in another insert statement but I can't get there because of the error from the first INSERT statement.

Please let me know if I need to clarify.
Thank  you
Hello Experts

I am getting a json response from a URL which I am trying parse it and capture code to store in the DB

Its returning the string ok but I am unable to remove the quoted strings to save the code in the DB

 Dim jResults As Object = JObject.Parse(Json)
        Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of String, Object))(Json)
        Dim firstItem = jsonResulttodict.Item("error")
        Dim seconditem = jsonResulttodict.Item("success")
        Dim thirditem = jsonResulttodict.Item("codes")

example string:

'{"error":"","success":"1 code generated successfully","codes":["QTESTA2HLT"]}

I am getting the code as [{  "QTESTA2HLT"  }]

Al I want is to read as QTESTA2HLT

please advise

Please show example to populate a text box with last I'd from a sql table(e.g. Employee)
I am trying to deserialize a string:


But it errors

The code I am using is
private void startToolStripMenuItem_Click(object sender, EventArgs e)
           string bal = RetrieveAccountBalance();
            AccountDetail Details = JsonConvert.DeserializeObject<AccountDetail>(bal);
       #region Account Methods

 public class AccountList
            public List<AccountDetail> data { get; set; }

        public class AccountDetail
            public string balance { get; set; }
            public string pendingFunds { get; set; }
            public string currency { get; set; }

Open in new window

Could anyone help with this error
I am a .NET Full Stack developer with UI experience, but little on Angular.

What's the best version to learn?

I want to learn that to maximize my value in the job market.

I am new to C#.
I am trying to get data from webpage

The table I am looking for is the Exchange Markets Table.

Could anyone help with the code.

If needed it could be pulled to an xml file then displayed in listview on a form.  I want this to be automated updating file at 1 minute intervals

Using DirectoryServices.DirectoryEntry class I'm trying to remove a user entry from a group in active directory using C# .NET

I came across two ways of doing that,

First way:

DirectoryEntry directoryEntry = new DirectoryEntry(myGroupPath);

Second way

DirectoryEntry directoryEntry = new DirectoryEntry(myGroupPath);
directoryEntry.Invoke("Remove", userDistinguishedName);

Acording to the msdn Invoke documentation, it says that Invoke Calls a method on the native Active Directory Domain Services object. How is it different than the first way?
Concerto's Cloud Advisory Services
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

I am fairly new to nHibernate and its the ORM of choice of the company I am working with.  I have created a new stored procedure that will get the data in one request rather than loop through and do upto 200 - 400 seperate databsase calls.  In doing so, this now needs a new process.  As nHibernate it the product of choice I thought it would be better to keep it as a standard.

So.. below is the structure that I have in place, i have changed schema to dbo and namespaces to xxx to keep identities simple and anonymous. Everything else is actual code and what I need help with.

The problem I get is when I try and complete the call to the stored procedure I get the error

Error message

could not execute query
  Name:MainDealer - Value: xxxxxxxx

Inner Exception


Stack Trace

[IndexOutOfRangeException: MainDealer2_0_]
   System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName) +1754202
   System.Data.SqlClient.SqlDataReader.GetOrdinal(String name) +101
   NHibernate.Driver.NHybridDataReader.GetOrdinal(String name) +11
   NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String name) +43
   NHibernate.Type.NullableType.NullSafeGet(IDataReader rs, String[] names, ISessionImplementor session, Object owner) +21
I'm get this error when try to get data from DataGridView by using stored procedure.
The stored procedures:

create proc [dbo].[ADD_LAB_RESULTS]
@ORDER_ID int,
@TESTID int,

create proc [dbo].[GET_GROUPID]
select groupid from Groups
where Groups.groupid = ''+ @TESTID +''
My C# code when click save button BtnSave:
this is the parameters void :

public void ADD_LAB_RESULTS(int sample_id, int order_id, int testid, int groupid,int SAMPLE_STATUS)
            DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
            SqlParameter[] param = new SqlParameter[5];
            param[0] = new SqlParameter("@sample_id", SqlDbType.Int);
            param[0].Value = sample_id;

            param[1] = new SqlParameter("@order_id", SqlDbType.Int);
            param[1].Value = order_id;

            param[2] = new SqlParameter("@testid", SqlDbType.Int);
            param[2].Value = testid;

            param[3] = new SqlParameter("@groupid", SqlDbType.Int);
            param[3].Value = groupid;


I want to know how to remove temp files after Response.End

If I add File.Delete(prcss_docPath) in the finally the download does not complete.

        string srcTemplate = String.Empty;
        string prcss_docPath = String.Empty;
        string dnNo = String.Empty;
             srcTemplate    = "FileSrc.docx"
            prcss_docPath = "File.docx";
            bool processed = false;
            File.Copy(srcTemplate, prcss_docPath, false);
            ContractProcess cps = new ContractProcess();
            processed = cps.ParseWordTemplate(prcss_docPath, dnNo);

            if (processed)
                 FileInfo file = new FileInfo(prcss_docPath);
                Response.ContentType = "Application/msword";
                Response.AppendHeader("Content-Disposition", "inline; filename=" + file.Name);
                Response.AppendHeader("Content-Length", file.Length.ToString());
        finally //Delete the files.


Open in new window

assume i have xml file call abc.xml

do you know any plug-in or app in c#/ that will create step by step form wizard based on the xml structure.
below we will start to read 'Notary' & 'CA' then i should have three steps

I just need some sort codes example to start.

          <Bond Name="Notary">
            <State name="CA"> 
              <Principal step="Step 1">
                <input type="text" class="" id="principalFirstName" placeholder="First Name" value=""></input>              
                <input type="text" class="" id="principalLastName" placeholder="Last Name" value=""></input>
                <input type="text" class="" id="principalMiddleName" placeholder="Middle Name" value=""></input>
                <input type="text" class="" id="principalCompanyName" placeholder="Company Name" value=""></input>
                <input type="text" class="" id="principalDBA" placeholder="DBA" value=""></input>
                <input type="text" class="" id="principalAddress" placeholder="Address" value=""></input>
                <input type="text" class="" id="principalCity" placeholder="City" value=""></input>
                <input type="text" class="" id="principalState" placeholder="State" value=""></input>
                <input type="text" class="" id="principalZip" placeholder="Zip" value=""></input>
                <input type="text" class="" id="principalPhoneNo" placeholder="Phone No" 

Open in new window

Hi Experts,

I am generating some labels as shown in Label1.png. My design is in Labeldesign.png.  My client needs the output in two columns as shown in Label_Desired.png. Please suggest is there any way to do it?

Thanks in advance.
So, I can access a file server in the network, I was given a login credentials- username and password.
I will specifically use this login/pw to access files in a server to allow reading and writing to this particular folder.
Windows authentication is used to login to the app.

I would like to switch to this  ID/pw given to me to authenticate and authorize writing and reading files to the server.

How would I sign in to this identity when I have to write and read files to this particular server? And then when I'm done, Ill switch it back to my original id/pw  identity?

I want to set Target Framework as .NET Standard 2.0 for my new .NET project. Where can I find the download so that I an install n my machine and use for new projects with .NET standard 2.0 as target .

Please se the attached,

Troubleshooting a piece of code.
            Dim web As Net.WebClient = New Net.WebClient()
            Dim html As String = web.DownloadString("")
            Dim m1 As Match = Regex.Match(html, "<span class=bld>\s*(.+?)\s*</span>", RegexOptions.Singleline)
            Dim currency As String = m1.Groups(1).Value.Replace("USD", "")


Open in new window

currency is blank.  

My question is what does "<span class=bld>\s*(.+?)\s*</span>", RegexOptions.Singleline" do?
I keep reading you can do C# on SPO (sandboxed solution). I make a small webpart that says hi, it deploys to my development site with no errors, but it doesnt look like it installs the feature. What gives ?
I then find an article that you can't do sandboxed soultions
In this article in mentions how to do it anyway (I think ?)
Can someone tell me if you can write a C# visual web part for SPO ? Definitavely ? I have to present this to management and I want to be correct.
Technology Partners: We Want Your Opinion!
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

In this code I am having the following problem.  Let's say that soOnly.ship_instruction_1 (which comes from a SQL view) is null, but OrdsToSend.ship_instruction_1 does not allow nulls.  At SubmitChanges it is going to fail and fall into the catch block.

When we move to the next order in the foreach and it reaches SubmitChanges, the values from the failed sumbit persist in the OrdsToSend object.

Originally this was written so that we "new up" OrdsToSend for each order within the foreach.  We changed it to set OrdsToSend to null for each order and in the catch block, but that doesn't help.

How can I "clear" the OrdsToSend object so that it accepts the values from the next order?

By the way, the null is completely invalid and should error.  It cannot "legally" be replaced by an empty string.  That's why we don't bother to check for nulls on any of the columns.


 private void TestCode()

                dcMydc dc = new dcMydc(this._ConnString);

                IQueryable<string> ordList = (from i
                                              in dc.CS13000_SubjectOrders
                                              orderby i.ord_no, i.inv_no, i.line_no
                                              select i.ord_no).Distinct();

                foreach (string order in ordList)
                    CS13000_SendOrd OrdsToSend = null;

I'm using C# with Visual Studio 2010 Windows Form.  In my program this works.

string str="";
str = string.Format("{0,-18}{1,-12}{2,-15}{3,-18}{4,-15}{5,-18}{6,-8}{7,-18}{8,-15}{9,-16}{10,-14}{11,-60}", l_s_symbol.ToString(), s_l_WTIDX, s_l_PIDX, s_l_NSIDX,  s_l_MVIDX,  s_l_FMVIDX, l_s_ClassID, l_s_CLS1, l_s_CLS2, l_s_CLS3, l_s_CLS4,  SecurityName);

Open in new window

I'd like to get the formatting from an external file since I will be running the program for different processes each of which have different information.  For example something like this which has failed where the string ReportDetail comes from a config file.

string str="";
string ReportDetail="{0,-18}{1,-12}{2,-15}{3,-18}{4,-15}{5,-18}{6,-8}{7,-18}{8,-15}{9,-16}{10,-14}{11,-60}", l_s_symbol.ToString(), s_l_WTIDX, s_l_PIDX, s_l_NSIDX,  s_l_MVIDX,  s_l_FMVIDX, l_s_ClassID, l_s_CLS1, l_s_CLS2, l_s_CLS3, l_s_CLS4,  SecurityName
str = string.Format(ReportDetail);

Open in new window

I am trying to do something similar to the app specs below.  I'm looking for a sample.  I thought I would use Core MVC,  Ajax and SQL server.  I'm looking for a sample that can show me each step.

It's pretty simple.
1. My app has a form with 4 fields. (Vin, Make, Model, Year)
2. I input Vin in field 1 (Vin)
3. I GET from a third party Rest API JSON by passing the Vin to a URI string. The string will pass Vin I input and an API key
4. The API returns (Make, Model, Year)
5. I want to fill the additional form fields with (Make, Model, Year)
6. Finally, I want to save all fields (Vin, Make, Model, Year), to my Database.

I have been searching for an example similar.  I did find the Weather app example, but it's not complete.  It's just part of it.
Weather example:
Hi experts,

I'm using ASP.NET MVC 5 with C#

On my view I have a DisplayFor displaying a datetime field.

My date time field is stored in sql server as datetime format

This is my current razor for this label on my page.

@Html.DisplayFor(m => m.MyTestDate)

With this syntax the browser displays this on my page.

07/17/2017 07:30:00 AM

Question 1: How do I format the razor DisplayFor tag to display only the date like this?:


Question 2: How do I format the razor DisplayFor tag to display only the time like this?:

07:30:00 AM
Hello Experts,
I am working on a Windows Service application in C#.  It is working fine in local machine.  I am getting the following error message when try to install in Production box.  I have set the Platform Target to Any CPU and Target Framework to .NET Framework 4.5. .  Also I tested it by changing the Platform Target to x86  and to x64.  But still getting the same error.  Please let me know how to fix it.  Thank you in advance.

Error Message
Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly 'file:///D:\Domains\XxxService\XxxPmtService.exe'
or one of its dependencies. An attempt was made to load a program with an incorrect format..

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>installutil -i D:\Domains\XxxService\XxxPmtService.exe
I have a Dymo .label file which is XML code and contains the code required to produce a label on a Dymo Labelwriter 450 printer. I need to convert this XML file to PDF so that I can send it to via an API so that I can print it Clientside. PrintNode will only except a PDF file. In my Server application I have copied the XML code out of the .label file and inserted into into a PDF file using iTextSharp as shown below.
The outcome is that I get a valid PDF file but when I open it , it contains the XML code from the .label rather than the formatted Label which I was expecting to see.  I am obviously missing some part of the conversion process but don't know what it is. Needless to can that if I send this file to printNode it will just print the XML text rather than the label. Any suggestions or pointers or examples would be welcome.


C# Code where I insert XML into PDF document                          
                           // Create new pdf file
                                fs = new FileStream(filePath1, FileMode.Create);
                            catch (Exception ex)

                            //To create a PDF document, create an instance of the class Document and pass the page size and the page margins to the 

Open in new window







C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).