john
john

Reputation: 121

create a file in Virtual Memory

Hi i am trying to upload a local into Sharepoint documentLibrary.

The following code works well to upload a file into document Libray.

    public void UploadFile(string srcUrl, string destUrl)
    {
        if (!File.Exists(srcUrl))
        {
            throw new ArgumentException(String.Format("{0} does not exist",
                srcUrl), "srcUrl");
        }

        SPWeb site = new SPSite(destUrl).OpenWeb();

        FileStream fStream = File.OpenRead(srcUrl);
        byte[] contents = new byte[fStream.Length];
        fStream.Read(contents, 0, (int)fStream.Length);
        fStream.Close();

        site.Files.Add(destUrl, contents);
    }

But i need to create a text file in document Library which contains a content like "This is a new file" without saving it in local disk.

Upvotes: 1

Views: 2412

Answers (3)

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262979

You can encode the string into a byte array and create the file from that array.

As an aside, note that your code leaks an SPSite and an SPWeb, which is quite dangerous since those objects can take a lot of memory. You need to properly dispose of them, e.g. with nested using statements:

using System.Text;

public void AddNewFile(string destUrl)
{
    using (SPSite site = new SPSite(destUrl)) {
        using (SPWeb web = site.OpenWeb()) {
            byte[] bytes = Encoding.GetEncoding("UTF-8").GetBytes(
                "This is a new file.");
            web.Files.Add(destUrl, bytes);
        }
    }
}

Upvotes: 1

Simon Mourier
Simon Mourier

Reputation: 138960

Something like that:

public void UploadText(string text, Encoding encoding, string destUrl)
{
    SPWeb site = new SPSite(destUrl).OpenWeb();
    site.Files.Add(destUrl, encoding.GetBytes(text));
}

PS: you will need an encoding to convert from a string to an array of bytes. You can hardcode one or pass it as a parameter just like I did.

Upvotes: 0

Cheng Chen
Cheng Chen

Reputation: 43523

You can use a MemoryStream instead of FileStream.

Upvotes: 4

Related Questions