Dropbox Online-Only files and C# FileIO Access - file-io

I have a folder that has thousands of files in it so i have Dropbox sync it as "Online-Only"
I've written a C# dotnet7 app to copy specific files to a separate folder.
foreach (var aFile in Files(srcroot))
{
var destFileName = #$"{destroot}{aFile.Name}";
if (!_fileSystem.File.Exists(destFileName))
{
_logger.LogInformation($"Copying File {aFile.FullName} -> {destFileName}");
_fileSystem.File.Copy(aFile.FullName, destFileName);
}
else
{
_logger.LogDebug($"Not Copying File Dest file already exists <-- {destFileName}");
}
}
But Keep Getting the same error messages
System.IO.IOException: The file cannot be accessed by the system. : 'C:\Dropbox (Personal)\Camera Uploads\2023-01-24 13.28.50.jpg'
at Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)
at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize, Nullable`1 unixCreateMode)
at System.IO.Strategies.OSFileStreamStrategy..ctor(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize, Nullable`1 unixCreateMode)
at System.IO.Abstractions.FileWrapper.Open(String path, FileMode mode, FileAccess access, FileShare share)
at Service.ImageCopier.Run() in C:\Users\mark.greenway\Desktop\Repos\DesktopToolsService\Service\ImageCopier.cs:line 64
at Service.DesktopToolsWorker.ExecuteAsync(CancellationToken stoppingToken) in C:\Users\mark.greenway\Desktop\Repos\DesktopToolsService\Service\Worker.cs:line 44
If I open the folder in Windows Explorer it downloads and copies without issue.
Is there a way to open or copy a file that will trigger the Dropbox "Online-Only" to download?

Related

Microsoft.WindowsAzure.Storage.StorageException: The operation has timed out

I have something like the following code
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
private void DownloadFile(CloudBlockBlob blobref , string fileName)
{
blobref.DownloadToFile( fileName, FileMode.Create);
}
It works most of the time
Then one day the following error occurs
Microsoft.WindowsAzure.Storage.StorageException: The operation has timed out. ---> System.TimeoutException: The operation has timed out.
at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 693
--- End of inner exception stack trace ---
at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 604
at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.DownloadToStream(Stream target, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 235
at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.DownloadToFile(String path, FileMode mode, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
The solution seems to be to re-generate the Storage Key
Is there a way to prevent this happening?

Xaml Designer not loading

today i've installed Visual Studio Community 2015 with Update 1 and when it try to load the Xaml Designer (even of a new project) it throws an exception:
An unhandled exception has occured
System.Runtime.InteropServices.COMException
The app did not start. (Exception from HRESULT: 0x8027025B)
at
Microsoft.VisualStudio.DesignTools.HostUtility.AppPackage.AppPackageNativeMethods.IApplicationActivationManager.ActivateApplication(String appUserModelId, String activationContext, ActivateOptions options, Int32& processId)
at
Microsoft.VisualStudio.DesignTools.HostUtility.AppPackage.DesignerWrtUtility.ActivateApplication(String appUserModelId, String activationContext, Object site, Boolean isRunningElevated)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.ActivateApplicationInternal(String appUserModelId, String activationContext, Object site)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.CreateDesignerProcess(String applicationPath, String clientPort, Uri hostUri, IDictionary environmentVariables, Int32& processId, Object& processData)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.ProcessIsolationDomain..ctor(ProcessDomainFactory factory, IIsolationBoundary boundary, AppDomainSetup appDomainInfo, IIsolationTarget isolationTarget, String baseDirectory)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
at
Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.Initialize()
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.CreateInstance[T](Type type)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedObjectFactory.Initialize()
at
Microsoft.VisualStudio.DesignTools.DesignerHost.Services.VSIsolationService.CreateObjectFactory(IIsolationTarget isolationTarget, IObjectCatalog catalog)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry, IServiceProvider serviceOverrides)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func'2 func, CancellationToken cancelToken)
at
Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.<>c__DisplayClass10_0'1.b__0()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
I had the same problem, this fixed it:
uninstall Visual Studio
uninstall all Windows SDKs/Emulators
install everything again
After that everything worked fine again.
If you're using an HP:
Delete the "Platform" environment variable in Control Panel > System > Advanced System Settings > Environment Variables [...] =HPD. (source)
If you're not using an HP, try following these steps:
Close any instance of Visual Studio
Open Visual Studio and create a new C# UWP empty project (name it whatever you want)
Run the newly created "useless" project, then close it as Visual Studio
Re-open your previous project. (source)
If you recently upgraded to the Windows 10 SDK from 10240 to 10586, then try setting the project Properties > Application > "Target version" to Windows 10 (10.0; Build 10240). (source)
Let me know if this helps!

Downloading files in Visual Studio

I am using the code recommended by Microsoft.
My.Computer.Network.DownloadFile("mydlurl", "C:\jb\jb.exe")
But that throws an unhandled exception on my friends computer, and some other people, but some can use it.
I tried using downloadasync with a progress bar, but it freezes before it even starts.(Does nothing)
Here is my code that runs an unhandled exception on some computers.
If My.Computer.FileSystem.FileExists("C:\jb\jb.exe") Then
Else
'jbinfo.Text = "Please wait as your file is being downloaded."
My.Computer.Network.DownloadFile("http://download1580.mediafire.com/g/abcdefghijklmnop/myfile.exe", "C:\jb\jb.exe", "", "", True, 500, True) '<Maybe fix. Lets try.
End If
The exception message is:
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.Net.WebException: The server committed a protocol violation. Section=ResponseStatusLine
at Microsoft.VisualBasic.MyServices.Internal.WebClientCopy.DownloadFile(Uri address, String destinationFileName)
at Microsoft.VisualBasic.Devices.Network.DownloadFile(Uri address, String destinationFileName, ICredentials networkCredentials, Boolean showUI, Int32 connectionTimeout, Boolean overwrite, UICancelOption onUserCancel)
at Microsoft.VisualBasic.Devices.Network.DownloadFile(String address, String destinationFileName, String userName, String password, Boolean showUI, Int32 connectionTimeout, Boolean overwrite, UICancelOption onUserCancel)
at Microsoft.VisualBasic.Devices.Network.DownloadFile(String address, String destinationFileName, String userName, String password, Boolean showUI, Int32 connectionTimeout, Boolean overwrite)
at MyApp.Main.Button1_Click_1(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
If I run this I get a ProtocolViolation, this is probably because DownloadFile expects a 200 OK, followed by the download, but Mediafire is sending you a 302 FOUND instead and redirects the request to a new location where the download page for this download is.
This is to prevent you from using MediaFire as a file hosting platform to distribute files without people actually knowing you're using MediaFire (makes sense right?).
You won't be able to use wc.DownloadFile or any other .NET framework method that expects a file here. You'll need to actually implement the proper 'handshake' with Mediafire so to speak, so they send you a new location, then go there and show that to the users.

Windows Azure Drive - Access Denied Exception

I am trying to write a test WCF service which writes image files into Azure Drive storage:
Below is the code I have written:
var storageAccount = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("mydrives");
container.CreateIfNotExist();
CloudPageBlob pageBlob = container.GetPageBlobReference("myvhd");
CloudDrive drive = new CloudDrive(pageBlob.Uri, storageAccount.Credentials);
try
{
drive.Create(100);
driveLetter = drive.Mount(0, DriveMountOptions.None);
var fileExtension = Path.GetExtension(file.FileName);
var fileName = string.Format("{0:10}_{1}{2}", DateTime.Now.Ticks, Guid.NewGuid(), fileExtension);
File.WriteAllBytes(driveLetter + "\\" + fileName, file.FileStream);
}
catch (CloudDriveException e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
file.FileStream is the byte array that I am getting from Silverlight client.
This code works perfectly when I run it locally. I could even see the drive blobs and images uploaded using the storage emulator viewer.
But as soon as I publish it to the cloud and run it, I get the following exception:
<InnerException i:nil="true"/><Message>Access to the path 'd:\1634586886770888071_aa98357b-888d-4dde-a231-1ca5d5c73b49.jpeg' is denied.</Message><StackTrace>
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
at ProcessService.FileService.UploadDCMToDrive(FileToTransfer file) in C:\Users\Vinod\Desktop\TestAzure_Vinod\ProcessService\FileService.svc.cs:line 68
at SyncInvokeUploadDCMToDrive(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><Type>System.UnauthorizedAccessException</Type>
I tried starting the application with elevated permissions (as per this) but I still get the same error. Can anyone shed some light on this please?
UPDATE: I created a folder using the below code:
DirectoryInfo di = new DirectoryInfo(driveLetter + "\\images");
if (!di.Exists)
di.Create();
Now I am getting this error:
Could not find a part of the path 'd:\images\test.jpeg
It's really weird :-(

Getting file permission on read while using MMF

I have two processes. One writing in a memory mapped file using .NET 4 MemoryMappedFiles and the other reading the file using FileStream in .NET 3.5 (MONO). Everything works fine when I get the permission, no problem reading or writing the file. The problem is to obtain a permission.
Writing MMF (the Writer):
MemoryMappedFile.CreateFromFile
(filenameToMap, FileMode.Create, "Something",
Marshal.SizeOf(objectToMap), MemoryMappedFileAccess.ReadWrite);
Reading MMF (the Reader):
new FileStream(filenameToMap, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
First I start the Writer, then the Reader.
I tested it using this naive approach:
while (true)
{
try
{
new FileStream(mapPath + "map.mp", FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite);
break;
}
catch { }
}
After roughly 10 seconds, the Reader usually gets permission and everything runs smooth. If I would catch the exception, it would throw:
IOException: Sharing violation on path
C:\path at
System.IO.FileStream..ctor
(System.String path, FileMode mode,
FileAccess access, FileShare share,
Int32 bufferSize, Boolean anonymous,
FileOptions options) [0x00000] in
:0
Any idea why these two processes don't share the file properly from beginning?