So I've been trying to use this piece of code below to try and upload an image into the SharePoint image library.
static NetworkCredential credentials = new NetworkCredential(username, password, domain);
static ClientContext clientContext = new ClientContext(siteURL);
static Web site = clientContext.Web;
static List list = site.Lists.GetByTitle("Site Images");
private static byte[] StreamFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
return ImageData;
}
private static void uploadImage()
{
String fileName = "Sunset";
String filePath = "C://Documents and Settings//Desktop//Sample Extracted Pic.jpeg";
list.RootFolder.Files.Add(fileName, StreamFile(filePath));
}
...And everything seems fine (at least within the compiler), until you get to: list.RootFolder.Files.Add(fileName, StreamFile(fileName));
The compiler returns an error saying No overload for method 'Add' takes 2 arguments, and I understand what it's saying, but I have no idea why I am getting that error. Does anyone have any idea or proposed solutions? All feedback is appreciated.
The client object model's Add method only has one parameter: FileCreationInformation. See this MSDN page for more details: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.filecollection.add.aspx
Related
Hello everyone I am making a simple web application that utilizes the users webcam and/or allows you to upload pictures. Please ignore the error in the images, it's done on purpose.
I get the Bytes of the Image like this:
Now I want to enter it into my Database with the SQL data type Image.
In my data access layer I have parameters that look like this:
.
public int AddParam(string ParamName, byte[] pic)
{
return AddParam( ParamName, pic);
}
I entered them and tried to execute it like this:
DataAccessLayer DataAccessLayer = new DataAccessLayer()
DataAccessLayer.PictureCaptured(dlStudentID.SelectedValue.ToString(),imgByte.ToArray());
DataSet ds = new DataSet();
DataAccessLayer .WebExecute(out ds);
It gives me an error like this:
I don't understand why it is doing that.
Please let me know if you have any tips or answers to it.
Thank You very much.
Use this method for converting image into bytes,
public byte[] ImageToByte(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}
If I had to guess, the method AddParams is calling itself over and over and over again which is why you received a StackOverFlowException:
https://msdn.microsoft.com/en-us/library/system.stackoverflowexception(v=vs.110).aspx
i have tried every possible solution that is given on website.
private byte[] GetBinaryFile()
{
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
return bytes;
}
This is what i was trying to Read from the fileuploader which didn't work. Then i changed the idea i uploaded the file on the server first and then i was trying to read but that again gave me the same error of system.byte(). Thing is it does not return the byte format of the pdf but it worked perfectly on my local system does it has anything to do with the server? Any help will be appreciated
you can try this:-
byte[] bytes = new byte[FileUpload1.PostedFile.ContentLength];
bytes = FileUpload1.FileBytes;
I'm having a problem getting a SOAP service to deserialize an array of objects; its only reading in the first member of the array and nothing else. Here is my code:
public void StoreCredentials(Credentials credentials)
{
Credentials[] credsArray;
var soap = new SoapFormatter();
var stream = new FileStream(_path, FileMode.OpenOrCreate);
try
{
credsArray = (Credentials[])soap.Deserialize(stream);
var credsList = credsArray.ToList();
credsList.Add(credentials);
credsArray = credsList.ToArray();
}
catch (SerializationException)
{
credsArray = new[] {credentials};
}
soap.Serialize(stream, credsArray);
stream.Close();
}
I wrote a simple unit test which adds two Credentials objects to the file, the output looks correct, both sets of credentials are present, but when I run the test to add a third set to the file, the soap.Deserialize(stream) line returns an array with only one entry, even though the file its reading from contains two entries. Am I doing something wrong here? Is there a better / easier way to do this? Please help!
I figured it out. The problem is with the FileMode.OpenOrCreate attribute of the FileStream. This will open the file but append it with a new collection instead of altering the original collection. I needed to overwrite the file by using FileMode.Create instead, so here is the working code (I also changed the collection to a Hashtable, which works better):
public void StoreCredentials(Credentials credentials)
{
credentials.Encrypt(_myUser.Encryption);
Hashtable credsTable;
var soap = new SoapFormatter();
FileStream stream;
try
{
stream = new FileStream(_path, FileMode.Open, FileAccess.ReadWrite);
credsTable = (Hashtable) soap.Deserialize(stream);
stream.Close();
stream = new FileStream(_path, FileMode.Create, FileAccess.ReadWrite);
if (credsTable.ContainsKey(credentials.Id))
credsTable[credentials.Id] = credentials;
else
credsTable.Add(credentials.Id, credentials);
}
catch (FileNotFoundException e)
{
stream = new FileStream(_path, FileMode.Create, FileAccess.ReadWrite);
credsTable = new Hashtable {{credentials.Id, credentials}};
}
soap.Serialize(stream, credsTable);
stream.Close();
}
I'm trying to convert a .db file to binary so I can stream it across a web server. I'm pretty new to C#. I've gotten as far as looking at code snippets online but I'm not really sure if the code below puts me on the right track. How I can write the data once I read it? Does BinaryReader automatically open up and read the entire file so I can then just write it out in binary format?
class Program
{
static void Main(string[] args)
{
using (FileStream fs = new FileStream("output.bin", FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
long totalBytes = new System.IO.FileInfo("input.db").Length;
byte[] buffer = null;
BinaryReader binReader = new BinaryReader(File.Open("input.db", FileMode.Open));
}
}
}
}
Edit: Code to stream the database:
[WebGet(UriTemplate = "GetDatabase/{databaseName}")]
public Stream GetDatabase(string databaseName)
{
string fileName = "\\\\computer\\" + databaseName + ".db";
if (File.Exists(fileName))
{
FileStream stream = File.OpenRead(fileName);
if (WebOperationContext.Current != null)
{
WebOperationContext.Current.OutgoingResponse.ContentType = "binary/.bin";
}
return stream;
}
return null;
}
When I call my server, I get nothing back. When I use this same type of method for a content-type of image/.png, it works fine.
All the code you posted will actually do is copy the file input.db to the file output.bin. You could accomplish the same using File.Copy.
BinaryReader will just read in all of the bytes of the file. It is a suitable start to streaming the bytes to an output stream that expects binary data.
Once you have the bytes corresponding to your file, you can write them to the web server's response like this:
using (BinaryReader binReader = new BinaryReader(File.Open("input.db",
FileMode.Open)))
{
byte[] bytes = binReader.ReadBytes(int.MaxValue); // See note below
Response.BinaryWrite(bytes);
Response.Flush();
Response.Close();
Response.End();
}
Note: The code binReader.ReadBytes(int.MaxValue) is for demonstrating the concept only. Don't use it in production code as loading a large file can quickly lead to an OutOfMemoryException. Instead, you should read in the file in chunks, writing to the response stream in chunks.
See this answer for guidance on how to do that
https://stackoverflow.com/a/8613300/141172
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.
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.