Create file on sharepoint

02/07/2014 15:56

//Create file from scratch - from memory stream


 using (StreamWriter writer = new StreamWriter(new MemoryStream()))
                    {
                        writer.WriteLine(allText);
                        writer.WriteLine("novy text 7");
                        writer.WriteLine("novy text 8");
                        writer.Flush();
   
   //write writer content to file on file system
                        using (var file2 = File.Open("fooTest.txt", FileMode.Append))
                        {
                            writer.BaseStream.Position = 0;
                            writer.BaseStream.CopyTo(file2);
                        }

   //write writer content to Sharepoint - create file
                        byte[] bytePackage = ToByteArray(writer.BaseStream);
              
                        // aby sme nasledne mohli ulozit byte[] do SharePoint kniznice
                        string fileName = string.Format("/MyFileName_{1:yyyy-MM-dd-HH-mm}.csv", DateTime.Now);

                        SPList targetList = web.Lists.TryGetList("My sharepoint list");
                        if (targetList != null)
                        {
                            targetList.RootFolder.Files.Add(targetList.RootFolder.Url + fileName, bytePackage, true);
                            targetList.Update();
                        }
                        else
                        {
                            throw new FileNotFoundException("Library doesn't exist at {0}", web.Url);
                        }
                    }


 public static byte[] ToByteArray(Stream stream)
        {
            stream.Position = 0;
            byte[] buffer = new byte[stream.Length];
            for (int totalBytesCopied = 0; totalBytesCopied < stream.Length; )
                totalBytesCopied += stream.Read(buffer, totalBytesCopied, Convert.ToInt32(stream.Length) - totalBytesCopied);
            return buffer;
        }