【解決方法】オフィス オートメーションを使用してオフィス ドキュメントのローカル パスを取得するにはどうすればよいですか


アクティブなドキュメントが OneDrive フォルダーの一部である場合、ドキュメントがローカルに保存されている場合でも、戻り値は URL になります。
私が探しているのは、OneDrive と同期されているかどうかに関係なく、アクティブなドキュメントのローカル パスを取得する解決策です。 したがって、取得する代わりに

「https://d.docs.live.net/ea373ad9f9c16144/myfolder/myfile.docx」

私は取得します
“c:\users\my username\OneDrive\myfolder\myfile.docx”

私が試したこと:

私が使用する方法は

VARIANT result;
VariantInit(&result);

m_hr = OLEMethod(DISPATCH_PROPERTYGET, &result, m_pActiveDocument, (LPOLESTR)L"Path", 0);

解決策 1

ここでは簡単で汚い解決策を紹介します。

OLECHAR* OfficeAutomation::GetActiveDocPath()
{
	VARIANT result;
	VariantInit(&result);

	m_hr = OLEMethod(DISPATCH_PROPERTYGET, &result, m_pActiveDocument, (LPOLESTR)L"Path", 0);

	if (FAILED(m_hr))
		return nullptr;

	BSTR url = result.bstrVal;

	// Check if the URL contains "https://", indicating it's a OneDrive URL
	if (wcsstr(url, L"https://") != nullptr)
	{
		// Get the current user account name
		wchar_t userName[UNLEN + 1];
		DWORD userNameSize = UNLEN + 1;
		GetUserNameW(userName, &userNameSize);

		// Check if the URL is a subfolder under the root OneDrive folder
		const wchar_t* rootFolder = L"https://d.docs.live.net/";
		const size_t rootFolderLen = wcslen(rootFolder);
		if (wcsstr(url, rootFolder) == url)
		{
			// Find the position of the first slash after the root folder
			const wchar_t* slash = wcschr(url + rootFolderLen, L'/');
			if (slash != nullptr)
			{
				// Find the position of the last slash to determine the folder path
				const wchar_t* lastSlash = wcsrchr(slash, L'/');
				if (lastSlash != nullptr)
				{
					// Extract the folder path and calculate its length
					const wchar_t* folderPath = slash + 1;
					size_t folderPathLen = lastSlash - folderPath;

					// Calculate the required buffer size for the local path
					size_t localPathSize = MAX_PATH + wcslen(userName) + folderPathLen + 11; // 11 for "\\OneDrive\\"

					// Allocate memory for the local path
					wchar_t* localPath = new wchar_t[localPathSize];
					wcscpy(localPath, L"C:\\Users\\");
					wcscat(localPath, userName);
					wcscat(localPath, L"\\OneDrive\\");
					wcsncat(localPath, folderPath, folderPathLen);

					// Replace forward slashes with backslashes in the local path
					wchar_t* backslash = wcschr(localPath, L'/');
					while (backslash != nullptr)
					{
						*backslash = L'\\';
						backslash = wcschr(backslash + 1, L'/');
					}

					// Convert the local path to BSTR
					BSTR resultPath = SysAllocString(localPath);

					// Clean up memory
					delete[] localPath;

					return resultPath;
				}
			}
		}
	}

	return url;
}

コメント

タイトルとURLをコピーしました