开发者

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 byt开发者_运维知识库e[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.


You can use a MemoryStream instead of FileStream.


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);
        }
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜