Monday, February 28, 2011

Add attachment to a list in share point

In share point we can upload the documents to the document library. this will be possible through the UI and through coding also. The below code shows how to add the documents to a list.
//Add attachments to document library.

        private static void AddItemsToDocumentLibrary(SPWeb currentWeb)
        {
            string fileName = string.Empty;
            long fileStreamLength;
            byte[] content;
            if (File.Exists("C:/ErrorLogFile.txt"))
            {
                using (FileStream fstream = File.OpenRead("C:/ErrorLogFile.txt"))
                {
                    fileStreamLength = fstream.Length;
                    content = new byte[fileStreamLength];
                    fstream.Read(content, 0, (int)fileStreamLength);
                    Console.WriteLine("enter the name that to be save as ");
                    fileName = Console.ReadLine();
                    if (string.IsNullOrEmpty(fileName))
                    {
                        Console.WriteLine("file name should not be empty or null");
                    }
                    else
                    {
                        currentWeb.Files.Add("http://localhost/Documents/" + fileName, content);
                        currentWeb.Update();
                    }
                    Console.WriteLine("File Saved in " + "http://localhost/Documents/" + fileName);
                }
            }
            else
            {
                Console.WriteLine("file not exist");
            }
        }



In the above code snippet we are giving the file location manually. It is "C:\ErrorLogFile.txt".
File.Exists , method checks the file exists or not. If the method. By using the byte array content we are reading the input file. By using the SPFile class Add() method we are uploading the file to document library.

Share this