programmatically Move and Check in local file to Sharepoint C# - c#

Below is code I am using to programmatically move a local file from D: to sharepoint library. I am able to move the file, but it does not check the file into sharepoint. I am unsure how to check this file in. Has anyone had similar issues with sharepoint? Thanks.
Here is my code, I did not use the exact destination and source urls, so ignore that. It compiles and runs fine and it can be used to move a file from lets say D: to My documents, it jsut does not check the file into sharepoint.
Also I am checking in an excel sheet that performs a number of calculation based on data updated daily. The calculations are done through a macro. Is it possible to write a macro to upload automatically to sharepoint library and check in? if so i can add this to the macro already in place instead of using c#. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.SharePoint.WorkflowServices;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
using System.Net;
namespace defectUpload
{
class Program
{
static void Main(string[] args)
{
string fileName = "WS2016.xlsm";
string sourcePath = # source path "";
string targetPath = # destination path "" ;
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
System.IO.File.Move(sourceFile, destFile);
}
}
}

This was already solved in this post https://sharepoint.stackexchange.com/questions/133197/excel-vba-code-to-upload-document-into-sharepoint-online-2013
Dim SharepointAddress As String
Dim LocalAddress As String
Dim objNet As Object
Dim FS As Object
' Where you will enter Sharepoint location path
SharepointAddress = "\\sharepoint path to document library" & "\"
' Where you will enter the file path, ex: Excel file
LocalAddress = "your file path"
Set objNet = CreateObject("WScript.Network")
Set FS = CreateObject("Scripting.FileSystemObject")
If FS.FileExists(LocalAddress) Then
FS.CopyFile LocalAddress, SharepointAddress
End If
Set objNet = Nothing
Set FS = Nothing
And also a good article on MSDN on this topic Using Microsoft Windows SharePoint Services with the Microsoft Office System.
There are also a lot of samples when you google for example for "vba upload to sharepoint"...

Related

C# WebClient.DownloadFile grabbing CSV from URL Format is not supported error.

quick question for you. I am trying to do a simple console application to grab a file from a URL. I wish I could say I know more about the site I'm grabbing it from, but all I know is that you put the parameters into the URL for which file you want, and when you go to the URL, you automatically start a download for it (this is what happens in a browser anyways).
So I used the code below and it does create a file but the only text in the file is the message below. I tried making the filename variable to the same as what the file name would be if you just downloaded it via the browser but that didn't work either, same error. Any ideas?
Error:
<?xml version="1.0" encoding="utf-8" ?><MtxExportingResult Result="Failure" Date="7/28/2015" Time="6:25:51 AM"><Error Type="FormatNotSupported">The format 'CSVExtract.csv' is not supported.</Error></MtxExportingResult>
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Net;
namespace ReceiveAndFormatCPCSV
{
class Program
{
static void Main(string[] args)
{
string remoteUri = "https://www.downloadurl.com/ServerEPS/Export/AllFileRecords.xpt?IdentifierNumber=666&username=Username&password=Password&format=CSV";
string fileName = "CPExtract.csv", myStringWebResource = null;
WebClient cpClient = new WebClient();
myStringWebResource = remoteUri + fileName;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
cpClient.DownloadFile(myStringWebResource, fileName);
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t");
}
}
}
any advice would be appreciated. Thank you,
The result of
myStringWebResource = remoteUri + filename;
is a badly formed URI which ends with "&format=CSVCPExtract.csv".
Delete that line and you should get different results. (Although you'll never catch me putting that URI into a browser or web client...it looks suspicious.)
The first argument to Download file is the URI to download the file from. The second is the local filename to download it to. Since your remoteUri includes parameters, and one of those parameters is IdentifierNumber, it appears that it points to a specific file. The code you copied and pasted off the web performs this concatenation because it plans to use the same local file name as the filename on the remote server.

C# how do I draw on files in the same location as i'm running the program without a long path

So far I haven't found anything that would allow my program to access text files that are in the same folder as it.
for example:
if my file is in C:/testingfolder i would need to use C:/testingfolder/filenames.txt to access the other files, the problem with this is sometimes it wont be in c:/testingfolder but instead it might be in E:/importantfiles or F:/backup and it needs to run from all of those.
If anyone could explain or give code that showed how to make a longer path into a "same folder" path that would answer my question.
With the Environment.CurrentDirectory you can get the path of your process that is executing, then you should use System.IO.Path.Combine() method to concatenate this path with the name of your file, and you will get the absolute location of your file.
You need to use System.IO and System.Text
using System;
using System.IO;
using System.Text;
then
static void Main(string[] args)
{
string line = "";
// look for the file "myfile.txt" in application root directory
using (StreamReader sr = new StreamReader("myfile.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
Console.ReadKey();
}

Cannot delete temporary file after File.Copy in C#

After copying a file to a temporary directory, I am unable to delete the copy because of an UnauthorizedAccessException exception. The idea here is to get a copy of the file, zip it and then delete the copy, but after removing all the code between File.Copy and File.Delete I am still getting the exception. Exiting from the program frees the lock and allows me to delete the copy without issue.
Is there a way to copy without causing this persistent lock (and preserve file metadata like LastModified)? Or a way to release the lock? Should there even be a lock on the copied file after File.Copy finishes?
I am using Visual C# 2010 SP1 targeting .NET Framework 4.0.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
namespace Test
{
class Program
{
static void Main(string[] args)
{
String FileName = "C:\\test.txt";
// Generate temporary directory name
String directory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
// Temporary file path
String tempfile = Path.Combine(directory, Path.GetFileName(FileName));
// Create directory in file system
Directory.CreateDirectory(directory);
// Copy input file to the temporary directory
File.Copy(FileName, tempfile);
// Delete file in temporary directory
File.Delete(tempfile);
}
}
}
Check your "C:\\test.txt" file for read only or not.
based on your comments this may be the reason you can copy but you can't delete
try with below
File.SetAttributes(tempfile, FileAttributes.Normal);
File.Delete(tempfile);
I see you've already found an answer, but I'll add this for reference anyway; A possible alternative approach for you, might be to create the copy in a memory stream instead of copying the file to your hard-drive.
Using the DotNetZip library, you could do something like this:
using (var ms = new MemoryStream())
{
using (var zip = new ZipFile())
{
zip.AddEntry(fileName, data);
zip.Save(ms);
}
}

How do you get subject & title from a Word document (without opening it)?

I would like to read the title and subject fields from a Word document, but would rather not have the overhead of firing up Word to do it.
If, in Windows Explorer, I display the title and subject columns, and then navigate to a folder that has Word documents in it, then this information is displayed. What mechanism is being used to do this (aside from Shell extensions) because its fast (but I don't know if you actually need Word installed for this to work), so I'm guessing its not firing up Word and opening each document.
I've found a link to Dsofile.dll, which I presume I could use, but does this work for .doc and .docx files and is it the only way ?
Well... as one might assume that the time of the ".doc" file is passing, here is one way to get the subject and title from a ".docx" file (or ".xlsx" file for that matter).
using System;
using System.IO;
using System.IO.Packaging; // Assembly WindowsBase.dll
namespace ConsoleApplication16
{
class Program
{
static void Main(string[] args)
{
String path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
String file = Path.Combine(path, "Doc1.docx");
Package docx = Package.Open(file, FileMode.Open, FileAccess.Read);
String subject = docx.PackageProperties.Subject;
String title = docx.PackageProperties.Title;
docx.Close();
}
}
}
I hope this is useful to someone.
You can read it via XML, too: How to extract information from Office files by using Office file formats and schemas
Here is another example on how to read a Word doc programmatically.
One way or the other you'll have to look inside the file at some point!

Read contents of a file using a relative path in a Web Application

How can I read the contents of a text file in my Web Application, using a relative path/URL?
The files are located in a directory at the root of my application.
I don't want to specify the full path to the file I want to access, since my test environment is not an exact mirror of my production environment.
Use Server.MapPath("/path/to/file") and pass the result of that to File.ReadAllText():
String template = File.ReadAllText(Server.MapPath("~/Templates/") + filename);
You can use this code snippet as well.
using System.IO;
using System.Web.Hosting;
using (StreamReader sr = new StreamReader(VirtualPathProvider.OpenFile("~/foo.txt")))
{
string content = sr.ReadToEnd();
}

Categories