Introduction
What type of file does your phone saves when u create a contact?
Well, the answer is: It stores it in a file format called vcard. Where vcard stands for "Virtual Contact Card".
At the time of writing this article., there are not a lot of nuget packages that can do this.
So, in this tutorial, we are going to create a vcard using C#.
Create a vcard using C#
Let's get started by creating a project on visual studio.
Click on new project and select "console application".
Click on continue and give it a name.
Click on continue and create a new folder naming it as "Helpers".
Then, create 2 new classes in the folder, naming them as "ImageHelper" and "FileHelper".
Again, Create a new folder naming it as "Models" and create a file naming it as "Contact.cs".
Add the following code to Contact.cs in order to store the contact.
Don't Forget to add system.collections.generic to the namespace (add the following code to the top of the file "using System.Collections.Generic;").
public class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FormattedName { get; set; }
public string Organization { get; set; }
public string Email { get; set; }
public string Title { get; set; }
public string Photo { get; set; }
public List<Phone> Phones { get; set; }
public List<Address> Addresses { get; set; }
}
public class Phone
{
public string Number { get; set; }
public string Type { get; set; }
}
public class Address
{
public string Description { get; set; }
public string Type { get; set; }
}
Now open ImageHelper.cs and make it as a static class and add the following code to convert the image URL to base64 format.
public static string ConvertImageURLToBase64(string url)
{
StringBuilder _sb = new StringBuilder();
Byte[] _byte = GetImage(url);
_sb.Append(Convert.ToBase64String(_byte, 0, _byte.Length));
return _sb.ToString();
}
static byte[] GetImage(string url)
{
Stream stream = null;
byte[] buf;
try
{
WebProxy myProxy = new WebProxy();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
stream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
int len = (int)(response.ContentLength);
buf = br.ReadBytes(len);
br.Close();
}
stream.Close();
response.Close();
}
catch (Exception exp)
{
buf = null;
}
return (buf);
}
The method ConvertImageURLToBase64 converts an URL containing an image to base64 format to place it in the vcard.
Now let's code the FileHelper class.
Open FileHelper.cs and add the following code to it.
This is the main class where we will convert the parameters into a vcard.
Don't forget to make it as a static class.
const string NewLine = "\r\n";
const string Separator = ";";
const string Header = "BEGIN:VCARD\r\nVERSION:2.1";
const string Name = "N:";
const string FormattedName = "FN:";
const string OrganizationName = "ORG:";
const string TitlePrefix = "TITLE:";
const string PhotoPrefix = "PHOTO;ENCODING=BASE64;JPEG:";
const string PhonePrefix = "TEL;TYPE=";
const string PhoneSubPrefix = ",VOICE:";
const string AddressPrefix = "ADR;TYPE=";
const string AddressSubPrefix = ":;;";
const string EmailPrefix = "EMAIL:";
const string Footer = "END:VCARD";
public static string CreateVCard(Contact contact)
{
StringBuilder fw = new StringBuilder();
fw.Append(Header);
fw.Append(NewLine);
//Full Name
if (!string.IsNullOrEmpty(contact.FirstName) || !string.IsNullOrEmpty(contact.LastName))
{
fw.Append(Name);
fw.Append(contact.LastName);
fw.Append(Separator);
fw.Append(contact.FirstName);
fw.Append(Separator);
fw.Append(NewLine);
}
//Formatted Name
if (!string.IsNullOrEmpty(contact.FormattedName))
{
fw.Append(FormattedName);
fw.Append(contact.FormattedName);
fw.Append(NewLine);
}
//Organization name
if (!string.IsNullOrEmpty(contact.Organization))
{
fw.Append(OrganizationName);
fw.Append(contact.Organization);
fw.Append(NewLine);
}
//Title
if (!string.IsNullOrEmpty(contact.Title))
{
fw.Append(TitlePrefix);
fw.Append(contact.Title);
fw.Append(NewLine);
}
//Photo
if (!string.IsNullOrEmpty(contact.Photo))
{
fw.Append(PhotoPrefix);
fw.Append(ImageHelper.ConvertImageURLToBase64(contact.Photo));
fw.Append(NewLine);
fw.Append(NewLine);
}
//Phones
foreach (var item in contact.Phones)
{
fw.Append(PhonePrefix);
fw.Append(item.Type);
fw.Append(PhoneSubPrefix);
fw.Append(item.Number);
fw.Append(NewLine);
}
//Addresses
foreach (var item in contact.Addresses)
{
fw.Append(AddressPrefix);
fw.Append(item.Type);
fw.Append(AddressSubPrefix);
fw.Append(item.Description);
fw.Append(NewLine);
}
//Email
if (!string.IsNullOrEmpty(contact.Email))
{
fw.Append(EmailPrefix);
fw.Append(contact.Email);
fw.Append(NewLine);
}
fw.Append(Footer);
return fw.ToString();
}
We have finished writing all the classes.
It's time to implement it.
Open Program.cs and clear all the code in the Main method.
Add the following Namespaces to your Program.cs file.
using VCard.Models;
using VCard.Helpers;
Now we can create a new contact with its parameters..
Contact contact = new Contact
{
FirstName = "Satvik",
LastName = "Rajnarayanan",
Addresses = new System.Collections.Generic.List<Address>()
{
{ new Address(){ Description="This is my Home Address..", Type="Home"} },
{ new Address(){ Description="This is my Work Address", Type="Work"} }
},
Phones = new System.Collections.Generic.List<Phone>()
{
{ new Phone(){ Number="0000000000", Type="Home"} },
{ new Phone(){ Number="0000000000", Type="Work"} }
},
Email = "[email protected]",
Organization = "CSharpCorner",
Photo = "https://www.c-sharpcorner.com/App_Themes/CSharp/Images/SiteLogo.png",
Title = "Satvik"
};
Now we have set the parameters.
We can get the vcard as a string using the following command.
string vcardcontents = FileHelper.CreateVCard(contact);
Now we have got the contents of the vcard as a string.
Let's write it into a file.
Make sure that the output file extension is .vcf
string SavePath = System.IO.Path.Combine(AppContext.BaseDirectory, "output.vcf");
System.IO.File.WriteAllText(SavePath, vcardcontents);
Console.WriteLine("File saved at " + SavePath.Trim());
So the full code in the main method in Program.cs looks like this.
Contact contact = new Contact
{
FirstName = "Satvik",
LastName = "Rajnarayanan",
Addresses = new System.Collections.Generic.List<Address>()
{
{ new Address(){ Description="This is my Home Address..", Type="Home"} },
{ new Address(){ Description="This is my Work Address", Type="Work"} }
},
Phones = new System.Collections.Generic.List<Phone>()
{
{ new Phone(){ Number="0000000000", Type="Home"} },
{ new Phone(){ Number="0000000000", Type="Work"} }
},
Email = "[email protected]",
Organization = "CSharpCorner",
Photo = "https://www.c-sharpcorner.com/App_Themes/CSharp/Images/SiteLogo.png",
Title = "Satvik"
};
string vcardcontents = FileHelper.CreateVCard(contact);
string SavePath = System.IO.Path.Combine(AppContext.BaseDirectory, "output.vcf");
System.IO.File.WriteAllText(SavePath, vcardcontents);
Console.WriteLine("File saved at " + SavePath.Trim());
Output
Summary
In this article, we have got the knowledge of how to create a vcard using C#.
Check out the source code for reference.
I'll create a nuget pacage that can do this work ASAP.
Thank You.